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

C++ Declaring an inherited constructor?

本文关键字:构造函数 继承 声明 C++      更新时间:2023-10-16

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

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) {
}
};

我在第 18 行 (SeaTransport(int)::Transportation(int,string,string)( 时遇到问题。

我收到的错误发生在我声明Transportation的桥上。

如代码所示,类Transportation是主体类,类SeaTransport继承Transportation的属性。

Transport::Transport(int, std::string
, std::string( +2 过载 不允许使用类型名称

此错误发生在 int

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

,并且此最后一个错误都发生在两个字符串变量中。

似乎您将范围和构造函数初始值设定项列表混合在一起。

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

必须声明SeaTransport构造函数才能获取所有参数,包括父类的参数(假设要将它们传递给基构造函数(:

SeaTransport(int port, int id, string company, string operator);

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

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

正如某位程序员先生所说,你的代码中有一个 Scope 问题, 我将尝试回答您的第二个问题,即如何在构造函数上添加特色变量。

与您对port属性执行的操作相同。

您可以在所有属性之前定义boatNumberint boadNumber = 0,然后,您将重载您的 构造函数,boatNumber(num)在初始值设定项运算符之后,int num在初始值设定项运算符之前。

class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
~Transportation(){}
};
class SeaTransport: public Transportation {
public:
int portNumber;
int boatNumber;
SeaTransport(int num, int port, int id, string company, string oper)
:Transportation(id, company, oper), boatNumber(num),portNumber(port)  {}
~SeaTransport(){}
};

但是,如果你想让事情更具体,你可以创建另一个派生自SeaTransport然后,如果需要,您将定义boat的数量和更多其他详细信息。

我会给你画一个实例:

class Boat: public SeaTransport {
public:
int boatNumber;
Boat(int bNum,int num, int port, int id, string company, string oper):
SeaTransport( num, port, id, company, oper),boatNumber(bNum){}
~Boat(){}
};