我正在尝试以下代码段,
#include <string>
class A {
protected:
std::string name;
public:
A(std::string name):name(){}
};
class B: public A {
public:
B() : A("B") {}
};
class C: public B {
public:
C(): A("C"){} //<-- this is not allowed, but I want to make C has its own name
};
显然,这是不允许的,实现此目标的最佳方法是什么?
最佳答案
重写B
的构造函数
B(const std::string& name = "B") : A(name) {}
是一种方式。在这里,我为其配备了默认值,因此它仍然充当默认构造函数。
关于c++ - C++可以初始化基类的基类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63704567/