C++继承的类设计问题

C++ class design issue on inheritance

本文关键字:问题 继承 C++      更新时间:2023-10-16

我继承了一些为Linux和Mac OS开发的代码。现在,我正在使用Visual Studio将其移植到Windows上。当我尝试使用Visual Studio 2010构建它时,我得到了下面列出的错误。 下面报告了简化类的结构。

考虑Node类:

class Node
{
public:
Node();    
virtual ~Node(){}
virtual bool isLeaf() const = 0;
/* other methods */
virtual vector<Node *>& getNodeList() const=0;
};

其中isLeafgetNodeList是纯虚拟方法。

然后LeafNode两个派生类

class LeafNode : public Node
{
public:
LeafNode(){ cout << "leaf constructor";}  
~LeafNode(){ cout << "leaf destructor";}
bool isLeaf() const { return true; }
vector<Node *>& getNodeList() const {}
};

它只实现了isLeaf方法,CompositeNode

class CompositeNode : public Node
{
public:
CompositeNode(){ cout << "CompositeNode constructor";}
~CompositeNode(){ cout << "CompositeNode destructor";}
bool isLeaf() const { return false;}
vector<Node *>& getNodeList() const{ 
return m_NodeList;
}
private:
vector<Node*> m_NodeList

};

它实现了两种纯虚拟方法。 如果我尝试使用Visual Studio构建此代码,则会出现以下错误:

error C4716: 'LeafNode::getNodeList()' : must return a value

我了解编译器,但我不知道如何处理这种情况。 我应该如何重新设计类来解决这个问题? 多谢。

我了解编译器,但我不知道如何处理这种情况。我应该如何重新设计类来解决这个问题?

LeafNode::getNodeList只能返回一个空列表。将其实现为:

vector<Node *>& getNodeList() const
{
static vector<Node *> empty;
return empty;
}

virtual void isLeaf() const = 0;

是不对的。使用更有意义:

virtual bool isLeaf() const = 0;