C++ 声明一个继承的构造函数?

Bao*_*ing 0 c++ inheritance constructor

我在为继承另一个类的属性的类定义构造函数时遇到困难

class Transportation {

public:
    int ID;
    string company;
    string vehicleOperator;

    Transportation(int,string,string) {
    }
};

class SeaTransport: public Transportation {

public:
    int portNumber;

    SeaTransport(int)::Transportation(int,string,string) {
    }
};
Run Code Online (Sandbox Code Playgroud)

第 18 行 ( SeaTransport(int)::Transportation(int,string,string))有问题。

我收到的错误发生在我声明的 pont 处Transportation

从代码中可以看出,类Transportation是主体类,类SeaTransport继承了 的属性Transportation

交通::交通(int, std::string, std::string)
+2 重载

不允许类型名称

这个错误发生在 int

typedef std::__cxx11::basic_string std::string
不允许类型名称

并且这个最终错误发生在两个字符串变量上。

Som*_*ude 5

看来您将作用域和构造函数初始值设定项列表混合在一起。

双冒号运算符::用于作用域,而后跟单个冒号和初始化列表的构造函数是初始化列表。

您必须声明SeaTransport构造函数以获取所有参数,包括父类的参数(假设您想将它们传递给基本构造函数):

SeaTransport(int port, int id, string company, string operator);
Run Code Online (Sandbox Code Playgroud)

然后在构造函数的定义(实现)中,您“调用”构造函数初始值设定项列表中的父构造函数:

SeaTransport(int port, int id, string company, string oper)
   : Transport(id, company, oper), // "Call" the parent class constructor
     portNumber(port)  // Initialize the own members
{
}
Run Code Online (Sandbox Code Playgroud)