我有下面這段代碼:
const成員函數
class Test{
private:
int id;
public:
Test(int v):id(v) {}
int getId() { return id;}; // however,I change this method signature
int getId() const { return id;};
and all the errors gone
};
struct compare{
bool operator()(const Test& t1, const Test& t2){
return t1.getId() < t2.getId(); // got error here
}
};
int main(int argc, char *argv[]){
set<Test, compare> s;
Test str[] = {Test(1), Test(2), Test(3)};
for (int i = 0; i < 3; ++i){
s.insert(str[i]);
}
for (set<Test>::iterator it = s.begin(); it != s.end(); ++it){
cout << it->getId() << "\n"; // got error here
}
return EXIT_SUCCESS;
}
我得到這個錯誤,當我調用的方法的getId()與代碼:
passing `const Test' as `this' argument of `int Test::getId()' discards qualifiers
我不知道爲什麼我需要const getId()方法來修復該錯誤?謝謝
關於「迭代器一個std ::組總是到對象的常量限定類型。」:即在C的任何版本指定被++標準或這取決於標準庫開發人員? – 2011-05-18 04:03:36
@Eugen:它在標準的第23.2.4p6節中指定(在C++ 0x中,編號可能在早期版本中有所不同)。 – 2011-05-18 04:11:17
@Eugen:在(C++ 0x FDIS)中指定23.2.4 p5關聯容器中的鍵是不可變的&p6'對於關聯容器,其中 的值類型與鍵類型相同,迭代器和const_iterator都是常量迭代器「。 – Xeo 2011-05-18 04:14:41