[英]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. Branch 和 Leaf 都是 Node 的子节点,但是当我尝试排在队列的顶部时,在最后一行。 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.
“q.top()”给了我错误“object 的类型限定符与成员 function get_decimal 不兼容”,我不知道为什么。 I have included Node branch and Leaf classes.
我已经包含了 Node 分支和 Leaf 类。
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. priority_queue::top()
返回对const
object ( const T &
) 的引用,但get_decimal()
未使用const
限定符声明,因此不能在const
object 上调用。 You need to add the const
qualifier:您需要添加
const
限定符:
int get_decimal() const // <-- HERE
{
return decimal_value;
}
You should do the same for your get_letter()
getter, too:你也应该对你的
get_letter()
getter 做同样的事情:
char get_letter() const
{
return letter;
}
You should also change your operator<
to take const Node &
references as well:您还应该更改您的
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.