2011-10-17 64 views
6

我試圖對包含int和字符串的向量進行排序在每個元素中。它是一個稱爲矢量食譜的類型向量。獲取上述錯誤,這裏是我的代碼:錯誤C2678:二進制'=':找不到操作符找到'const Recipe'類型的左手操作數(或沒有可接受的轉換)

在我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; 
}; 

我做錯了什麼?

+1

顯示我們對您得到這個錯誤行... –

+0

您確定要排序的字符串值,而不是配方ID? –

+0

我加了一個[tag:C++]標籤;它應該引起這個問題更多的關注。 –

回答

6

Menu::show()宣佈爲const,所以其內部的Menu::recipes被認爲已被宣告爲std::vector<Recipe> const

顯然,分選std::vector<>發生變異,所以Menu::show()切不可const(或Menu::recipes必須mutable,但這似乎不正確的語義在這種情況下)。

+0

這實際上是有意義的,並解釋了賦值編譯器錯誤。 –

0

您已將您的顯示方法標記爲const,這不是真實的,因爲它正在更改食譜矢量。當我編譯你用gnu gcc 4.2.1概述的代碼時,錯誤是特定於取消限定符的限定符,而不是你發佈的錯誤。

你可以使用關鍵字mutable來標記你的向量,但我懷疑這不是你真正想要的嗎?通過將矢量標記爲可變,它將忽略編譯器通常在矢量的Menu::show() const內執行的常量,並且每次調用Menu :: show()時它都會被更改。如果你真的想使用這個向量,而不是像其他人那樣的有序集合,你可以添加一個骯髒的狀態標誌來讓你的程序知道什麼時候應該使用或不使用。

下面的代碼我通過將矢量更改爲mutable來展示差異來編譯,但我仍建議您不要使用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()); 
} 
+0

比較器__應該通過'const&'(和它的'operator()'本身應該是'const')來引用參數。問題是他的'vector '是'const'。 – ildjarn

+0

vector 沒有標記爲const,它只具有const語義,因爲show()方法標記爲const。這就是爲什麼我建議使用mutable關鍵字來限定向量類型。 – James

+0

我明白,我只是說淨效應是一樣的。 – ildjarn

相關問題