c++ - 我从子类中的函数中得到了不正确的值。我是否错误地设置了它的构造函数?
问题描述
#include <iostream>
#include <vector>
using namespace std;
class road {
public:
road(){};
void setname(string n) {
name = n;
};
void settype(string t) {
type = t;
};
void setspeedlimit(int s) {
speedlimit = s;
};
virtual void print() {
cout << name << " is of type " << type << " and has speedlimit " << speedlimit;
};
string gettype() {
return type;
};
string name;
string type;
int speedlimit;
string owner;
int lanes;
};
class mainroad : public road {
public:
mainroad(string o) {
owner = o;
};
virtual void print() {
cout << owner;
};
};
class secondaryroad : public road {
public:
secondaryroad(int l) {
l = lanes;
};
virtual void print() {
cout << lanes;
}
};
int main(void) {
vector<road> v;
secondaryroad x11(2), rt3(1), rr5(1);
x11.setname("old farm");
x11.setspeedlimit(20);
x11.settype("secondary");
rt3.setname("the pike");
rt3.setspeedlimit(10);
rt3.settype("secondary");
rr5.setname("wagon trail");
rr5.setspeedlimit(10);
rr5.settype("secondary");
mainroad n1("feds"), s1("state"), ri1("state");
n1.setname("usa6");
n1.setspeedlimit(0);
n1.settype("main");
s1.setname("montana 5");
s1.setspeedlimit(100);
s1.settype("main");
ri1.setname("rhody 7");
ri1.setspeedlimit(55);
ri1.settype("main");
v.push_back(x11);
v.push_back(n1);
v.push_back(s1);
v.push_back(rt3);
v.push_back(ri1);
v.push_back(rr5);
for (auto x : v) {
x.print();
if (x.gettype() == "main") {
std::cout << " This road is owned by " << x.owner << "\n";
} else {
std::cout << " This road has " << x.lanes << " lanes\n";
}
}
return 0;
}
在运行时,我收到 -858993460 条车道。之前我遇到了一个问题,这个数字也会出现在我的速度限制中。我设置secondaryroad子类的方式不正确吗?还是 .lanes 段甚至可以识别任何数字?此外,我的所有变量都在公共域中,但我在尝试让 main 函数能够与变量所有者和通道交互时遇到了麻烦。这是因为它们在基类中没有构造函数吗?对于加载的问题,我很抱歉,我对 c++ 和一般编程有点陌生。
解决方案
推荐阅读
- python - 如何从列表中的条目中删除“\n”?
- git - Docker-compose 与自定义目录中托管在 git 中的图像
- json - Circe 无法将原始 json 转换为案例类错误:找不到 io.circe.generic.decoding.DerivedDecoder 类型的惰性隐式值
- java - 检查字符串是否包含@符号或字符串是否为空
- angular - 处理和测试深层或受保护的路由/功能的解决方案
- c - 如何释放更复杂的嵌套结构
- java - ArrayList[] 需要未经检查的转换以符合 ArrayList
[] - javascript - 成功 requestStorageAccess() 调用后,Firefox Storage Access API 拒绝本地存储
- excel - Excel 到 SAP 图形用户界面
- javascript - 评估错误:由 JavaScript 探针错误引起