c++ - 对象具有不兼容的类型限定符,可能是继承/多态错误?
问题描述
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 类。
解决方案
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;
}
推荐阅读
- javascript - 用玩笑模拟条件 window.open 函数调用
- python - 过滤 Pandas DataFrame 中的特定值
- angular - 将 *ngFor 动态添加到 HTML 元素
- python-3.x - 使用 tf-coreml 将 Tensorflow 转换为 CoreML
- java - Spring boot 2 embed tomcat 9.0.26 无法加载jks文件流关闭
- ruby-on-rails - 通过 created_at 对关联模型进行分组和计数
- c++ - 如何简化模板模板参数中的 enable_if 别名
- multithreading - 如何在不创建静态函数的情况下调用线程
- android - Android - Searchview 只能进行一次搜索
- heroku - Heroku-18 w/.NET Core GDI+:无法加载 DLL 'libgdiplus':找不到指定的模块