我收到了:
//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
的构造函数中出现了错误:
难道不是应该通过 Element 来初始化 Node 吗?为什么编译器要求我在那里显式初始化?'SpecificElement' 的构造函数必须显式初始化基类 'Tree::Node',但该类没有默认构造函数
我不知道这是否与 builders 保护有任何关系。或者是否与命名空间有关,尽管我认为不是,因为代码已经编译通过,直到我引入了
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
}
};
}