【发布时间】:2020-07-19 04:56:41
【问题描述】:
我正在尝试打印优先级队列,但它给了我以下错误:
[错误] 将 'const value_type {aka const Horse}' 作为 'void Horse::print()' 的 'this' 参数传递会丢弃限定符 [-fpermissive]
这是我的代码的布局方式:
struct horse {
std::string horseName;
int win;
void print() {
std::cout<<"name: " << horseName<<std::endl;
}
bool operator < (Horse h) const {
if (h.win < win)
return true;
return false;
}
};
class Horses {
public:
std::vector<Horse> horses;
void printPriorityQ(std::priority_queue<Horse> q) {
while (!q.empty()) {
q.top().print();
q.pop();
}
std::cout << std::endl;
}
void testing();
};
这就是我使用它的方式:
void Horses::testing() {
Horse h;
h.horseName = "max";
h.win = 3;
horses.push_back(h);
h.horseName = "bob";
h.win = 3;
horses.push_back(h);
std::priority_queue<Horse> winner;
for (size_t i=0; i<horses.size(); i++)
results.push(horses[i]);
printPriorityQ(results);
}
我的预期输出应该是根据我的 horse 结构中 win 变量的顺序打印马名。
编辑:我的重载运算符正确吗? 我在下面的 cmets 的另一个线程上看到他们将其写为:
bool operator < ( const Horse& h, const Horse& hh) const {
if (h.win < hh.win)
return true;
return false;
}
【问题讨论】:
-
尝试在该线程stackoverflow.com/questions/19535644/…中提到的类之外声明运算符
-
下一次,请尝试编写一个重现您的问题的最小示例。这个过程通常会让你自己发现问题,但也为我们读者省去了阅读和理解其余代码的麻烦。此外,您应该在问题(或答案)中格式化您的代码,并使用适当的缩进使其可读。
标签: c++