我有下面这段代码:
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