【问题标题】:Object has type qualifiers that are not compatible, possible inheritance/polymorphism mistake?对象具有不兼容的类型限定符,可能是继承/多态错误?
【发布时间】:2019-10-23 20:15:38
【问题描述】:
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 类。

【问题讨论】:

  • 附带说明,tree_builder() 应该通过引用而不是值来获取 priority_queue。它正在泄漏news 的对象。还有Q.push(*b1)slices the Branch object。由于您试图在队列中存储多态类,因此您需要在队列中使用 Node* 指针,而不是 Node 对象。

标签: c++ inheritance polymorphism


【解决方案1】:

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

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

你也应该为你的 get_letter() getter 做同样的事情:

char get_letter() const
{
    return letter;
}

您还应该更改您的 operator&lt; 以获取 const Node &amp; 引用:

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

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多