【问题标题】:error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const Recipe' (or there is no acceptable conversion)错误 C2678:二进制“=”:未找到采用“const 配方”类型的左侧操作数的运算符(或没有可接受的转换)
【发布时间】:2011-12-09 16:21:42
【问题描述】:

我正在尝试对每个元素中包含一个 int 和一个字符串的向量进行排序。它是一个类类型的向量,称为向量配方。收到上述错误,这是我的代码:

在我的 Recipe.h 文件中

struct Recipe {
public:
    string get_cname() const
    {
        return chef_name;
    }
private:
    int recipe_id;
    string chef_name;

在我的 Menu.cpp 文件中

void Menu::show() const {
    sort(recipes.begin(), recipes.end(), Sort_by_cname());
}

在我的 Menu.h 文件中

#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;
};

我做错了什么?

【问题讨论】:

  • 向我们展示您遇到该错误的行...
  • 您确定要按字符串值而不是配方 ID 进行排序吗?
  • 我添加了c++标签;它应该引起这个问题的更多关注。
  • 您是否考虑过使用集合而不是向量?这样它就默认排序了,你不必让它可变。

标签: c++ class sorting vector


【解决方案1】:

Menu::show() 被声明为const,因此在其中Menu::recipes 被认为已被声明为std::vector&lt;Recipe&gt; const

显然,对std::vector&lt;&gt; 进行排序会使它发生变异,因此Menu::show() 不能是const(或Menu::recipes 必须是mutable,但在这种情况下这在语义上似乎不正确)。

【讨论】:

  • 这实际上是有道理的,并解释了赋值编译器错误。
【解决方案2】:

您已将 show 方法标记为 const,这是不正确的,因为它正在更改食谱向量。当我编译您使用 gnu gcc 4.2.1 概述的代码时,该错误特定于取消 const 限定符的资格,而不是您发布的错误。

您可以使用关键字mutable 标记您的向量,但我怀疑这不是您真正想要的?通过将向量标记为可变,它会忽略编译器通常会在向量的Menu::show() const 内强制执行的常量,并且每次调用 Menu::show() 时都会更改它。如果你真的想使用向量,而不是像其他人建议的有序集合,你可以添加一个脏状态标志,让你的程序知道什么时候应该使用,或者不使用。

我通过将向量更改为 mutable 以向您显示差异来编译以下代码,但我仍然建议您不要将 sort from 与 const show 方法一起使用。

#include <vector>
#include <string>

using namespace std;
struct Recipe {
public:
  string get_cname() const
  {
    return chef_name;
  }
private:
  int recipe_id;
  string chef_name;
};

class Menu {
public:
  void show() const;
private:
  mutable vector<Recipe> recipes;
};

struct Sort_by_cname
{
  bool operator()(const Recipe& a, const Recipe& b)
  {
    return a.get_cname() < b.get_cname();
  }
};

void Menu::show() const {
  sort(recipes.begin(), recipes.end(), Sort_by_cname());
}

【讨论】:

  • 比较器应该接受const&amp;的参数(并且它的operator()本身应该是const);问题是他的vector&lt;Recipe&gt;const
  • vector 没有标记为 const,它只有 const 语义,因为方法 show() 标记为 const。这就是为什么我建议使用 mutable 关键字来限定向量类型。
  • 我明白了,我只是说净效果是一样的。
猜你喜欢
  • 2015-11-18
  • 2017-03-17
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
相关资源
最近更新 更多