简体   繁体   中英

Object has type qualifiers that are not compatible, possible inheritance/polymorphism mistake?

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 and Leaf are both children of Node, however on the very last line when I try to cout the top of my queue. The "q.top()" is giving me the error "the object has type qualifiers that are not compatible with member function get_decimal" and I'm not sure why. I have included Node branch and Leaf classes.

priority_queue::top() returns a reference to a const object ( const T & ), but get_decimal() is not declared with the const qualifier so it cannot be called on a const object. You need to add the const qualifier:

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

You should do the same for your get_letter() getter, too:

char get_letter() const
{
    return letter;
}

You should also change your operator< to take const Node & references as well:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM