派生类未被识别为协变

时间:2017-04-14 16:26:44

标签: c++ inheritance override covariance

所以我正在创建一个霍夫曼树,我很难重写一个函数,我相信这是由于协方差问题。这是我在代码中遇到困难的层次结构:

class TreeInterface {
public:

    TreeInterface() {}
    virtual ~TreeInterface() {}

    virtual NodeInterface * getRootNode() const = 0;
};

class Tree : TreeInterface
{
public:
    Tree() 
    {}
    virtual ~Tree() 
    {}

    Node* getRootNode()
    {
        return treeRoot;
    }

    private:
    Node* treeRoot;
};

那些工作得很好,但它是下一个有问题的块。

class HuffmanInterface{
public:
    HuffmanInterface() {}
    virtual ~HuffmanInterface() {}

    virtual bool createTree(string filename) = 0;

    virtual string encodeMessage(string toEncode) = 0;

    virtual TreeInterface * getTree() = 0;

    virtual map<char, string> getEncodings() = 0;
};
class Huffman : HuffmanInterface{
public:

    Huffman() {}
    ~Huffman() {}

bool Huffman::createTree(string filename){ }

string Huffman::encodeMessage(string toEncode){ }

string Huffman::decodeMessage(string toDecode){ }

Tree* Huffman::getTree(){ }

map<char, string> Huffman::getEncodings(){ }

所以问题显然在getTree()函数中,给出了以下错误

invalid covariant return type for ‘virtual Tree* Huffman::getTree()’:
Tree * getTree();

但据我所知,Tree *应该是TreeInterface *的有效协变量。用TreeInterface *替换Tree *会使程序编译,但它不是我在实际程序中所需要的。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

class Tree : TreeInterface { ... };

相当于

class Tree : private TreeInterface { ... };

您需要进行继承public

class Tree : public TreeInterface { ... };