C++ 声明继承的构造函数?
C++ Declaring an inherited 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) {
}
};
我在第 18 行 (SeaTransport(int)::Transportation(int,string,string)
( 时遇到问题。
我收到的错误发生在我声明Transportation
的桥上。
如代码所示,类Transportation
是主体类,类SeaTransport
继承Transportation
的属性。
, 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
属性执行的操作相同。
您可以在所有属性之前定义boatNumber
为int 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(){}
};
相关文章:
- 具有相同名称的类的构造函数继承
- 多复制构造函数继承中的惊人行为
- CRTP 和复制/移动赋值/构造函数继承
- 复制构造函数继承动态分配的数组
- 无法从 c++ 中的构造函数继承
- 在构造函数继承中使用默认构造函数
- 构造函数继承和直接成员初始化
- C++ - 使用私有参数的构造函数继承
- 通过可变参数模板进行C++11构造函数继承
- C++11构造函数继承和不带参数的构造函数
- C++11 - 构造函数继承
- C++构造函数继承
- 使用 C++11 编译器的构造函数继承正在生成错误
- 选择性构造函数继承"Ambiguous resolution"错误
- 什么是构造函数继承
- C++对象中的构造函数继承与方法继承
- C++构造函数继承没有匹配的函数
- C++构造函数继承(从派生类调用构造函数)
- 模板构造函数继承的标准符合语法是什么
- C++构造函数继承错误