[英]Object has type qualifiers that are not compatible with the member function
[英]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 和 Leaf 都是 Node 的子節點,但是當我嘗試排在隊列的頂部時,在最后一行。 “q.top()”給了我錯誤“object 的類型限定符與成員 function get_decimal 不兼容”,我不知道為什么。 我已經包含了 Node 分支和 Leaf 類。
priority_queue::top()
返回對const
object ( const T &
) 的引用,但get_decimal()
未使用const
限定符聲明,因此不能在const
object 上調用。 您需要添加const
限定符:
int get_decimal() const // <-- HERE
{
return decimal_value;
}
你也應該對你的get_letter()
getter 做同樣的事情:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.