错误C2678:二进制'=':未找到采用'const Recipe'类型的左操作数的运算符(或没有可接受的转换) [英] error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const Recipe' (or there is no acceptable conversion)
问题描述
我正在尝试对一个向量进行排序,该向量在每个元素中包含一个int和一个字符串.它是称为矢量配方的类类型的矢量.收到上述错误,这是我的代码:
I'm trying to sort a vector that contains an int and a string in each element. It is a vector of class type called vector recipes. Getting the above error, here's my code:
在我的Recipe.h文件中
In my Recipe.h file
struct Recipe {
public:
string get_cname() const
{
return chef_name;
}
private:
int recipe_id;
string chef_name;
在我的Menu.cpp文件中
In my Menu.cpp file
void Menu::show() const {
sort(recipes.begin(), recipes.end(), Sort_by_cname());
}
在我的Menu.h文件中
In my Menu.h file
#include <vector>
#include "Recipe.h"
using namespace std;
struct Sort_by_cname
{
bool operator()(const Recipe& a, const Recipe& b)
{
return a.get_cname() < b.get_cname();
}
};
class Menu {
public:
void show() const;
private
vector<Recipe> recipes;
};
我在做什么错了?
推荐答案
Menu::show()
被声明为const
,因此在其内部Menu::recipes
被视为已声明为std::vector<Recipe> const
.
Menu::show()
is declared const
, so inside of it Menu::recipes
is considered to have been declared as std::vector<Recipe> const
.
很明显,对std::vector<>
进行排序会使它变异,因此Menu::show()
一定不能是const
(或者Menu::recipes
一定是mutable
,但是在这种情况下在语义上似乎是错误的).
Obviously, sorting a std::vector<>
mutates it, so Menu::show()
must not be const
(or Menu::recipes
must be mutable
, but this seems semantically incorrect in this case).
这篇关于错误C2678:二进制'=':未找到采用'const Recipe'类型的左操作数的运算符(或没有可接受的转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!