类的构造函数必须显式初始化基类
Constructor for class must explicitly initialize the base class
我得到了:
//all classes are in different files
namespace Tree {
class Node {
NodeType type;
protected:
std::string nodename;
Node(Node::NodeType _type) : type(_type) {}
};
}
class Parent : public virtual Tree::Node {
protected:
Parent() : Node(Node::UNDEFINED) {}
};
class Child: public virtual Tree::Node {
protected:
Child() : Node(Node::UNDEFINED) {}
};
namespace Tree {
class Element :
public Parent,
public Child,
public virtual Node {
protected:
Element() : Node(Node::ELEMENT) {}
};
}
class SpecificElement: public Tree::Element {
public:
SpecificElement(const std::string name) {
nodename = name;
}
};
在SpecificElement
的构造函数中出现错误:
"SpecificElement"的构造函数必须显式初始化基 类 'Tree::Node' 没有默认构造器
Node不应该通过Element初始化吗?,为什么编译器要求我在那里显式初始化?
我不知道这是否与被保护的建筑商有关。或者如果是用于命名空间,尽管我不这么认为,因为代码已编译,直到我引入了类SpecificElement
.
我会在SpecificElement
中调用 Node 的构造函数,但我有更多的类继承自此,并且都要求我显式初始化 Node,而我无法通过设计做到这一点。
编辑:感谢@r-sahu,我解决了如下
namespace Tree {
class Node {
protected:
std::string nodename;
NodeType type; //changed to protected
Node(Node::NodeType _type) : type(_type) {}
Node() : Node(UNDEFINED) {} //default constructor
};
}
namespace Tree {
class Element :
public Parent,
public Child,
public virtual Node {
protected:
Element() { //change the init constructor list
type = Node::ELEMENT; //change type inside constructor
}
};
}
Node
不应该通过Element
初始化吗?,为什么编译器要求我在那里显式初始化?
不。
仅当您创建Element
的实例而不是Element
的子类时,才会发生这种情况。这与virtual
继承有关。
virtual
继承的类必须在派生最多的类的构造函数中正确初始化。 因此,您必须使用:
SpecificElement(const std::string name) : Tree::Node(Node::ELEMENT) {
nodename = name;
}
有了这个,当你构造一个SpecificElement
的实例时,Tree::Node
子对象只初始化一次,从SpecificElement
的构造中初始化一次。Element
构造函数中的Tree::Node(Node::Element)
部分在运行时被忽略。
这种行为的理由可以在第 12.6.2 节初始化基和成员/10.1 中的标准中找到
相关文章:
- C++初始化基类
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 使用成员的地址初始化基类是否合法?
- 初始化基类成员 (c++) 的首选方法
- 类的构造函数必须显式初始化基类
- OOP - 抽象类类型,初始化基类和派生类中的变量
- 初始化基类和派生类中的类成员变量
- 为什么 C++ 的创建者决定使用构造函数初始值设定项列表来初始化基类?
- 通过drived类模板值通过基类构造器初始化基类数组成员变量
- 使用派生的[C++]生成的参数初始化基类
- C++ 在派生类中初始化基类的 const int?
- C++是否要求您从其派生类初始化基类成员
- 通过 CRTP 使用派生类变量初始化基类静态常量变量
- 初始化基类,派生类的构造函数中没有默认构造函数
- 我可以调用一个虚拟函数来初始化基类子对象吗
- 如何初始化基类构造函数的向量
- 初始化基类
- 在派生类的构造函数的主体中初始化基类成员变量
- 初始化基类的引用成员