首页 > 解决方案 > 我从子类中的函数中得到了不正确的值。我是否错误地设置了它的构造函数?

问题描述

#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++ 和一般编程有点陌生。

标签: c++

解决方案


推荐阅读