首页 > 解决方案 > 对象具有不兼容的类型限定符,可能是继承/多态错误?

问题描述

class Node
{
protected:
    int decimal_value;
    char letter;
public:
    Node(int decimal, char lett) : decimal_value(decimal), letter(lett)
    {}
    Node() :decimal_value(0), letter(NULL)
    {}
     int get_decimal()
    {
        return decimal_value;
    }
    char get_letter()
    {
        return letter;
    }
    void set_decimal(int n)
    {
        decimal_value = n;
    }
    void set_letter(char l)
    {
        letter = l;
    }
    friend bool operator<( Node& p1, Node& p2)
    {
        return p1.decimal_value > p2.decimal_value;
    }
    virtual ~Node() {};
};
class Leaf :public Node
{
    using Node::Node;

};
class Branch :public Node
{

    Node* left;
    Node* right;
public:

    Branch(Node* l, Node* r) :left(l), right(r)
    {
        decimal_value = l->get_decimal() + r->get_decimal();

    }

};
void tree_builder(priority_queue<Node> Q)
{
    Node* qleft=new Leaf;
    Node* qright= new Leaf;
    while (Q.size() > 1)
    {
        *qleft = Q.top();
        Q.pop();
        *qright = Q.top();
        Q.pop();
        Branch* b1 = new Branch(qleft, qright);
        Q.push(*b1);

        cout << Q.top().get_decimal();
    }




}

Branch 和 Leaf 都是 Node 的子节点,但是当我尝试排在队列的顶部时,在最后一行。“q.top()”给了我错误“对象具有与成员函数 get_decimal 不兼容的类型限定符”,我不知道为什么。我已经包含了 Node 分支和 Leaf 类。

标签: c++inheritancepolymorphism

解决方案


priority_queue::top()返回对const对象 ( const T &) 的引用,但未get_decimal()使用限定符声明,const因此无法在const对象上调用它。您需要添加const限定符:

int get_decimal() const // <-- HERE
{
    return decimal_value;
}

你也应该对你的get_letter()吸气剂做同样的事情:

char get_letter() const
{
    return letter;
}

您还应该更改您operator<const Node &引用:

friend bool operator<(const Node& p1, const Node& p2)
{
    return p1.decimal_value > p2.decimal_value;
}

推荐阅读