我有以下代码:
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
我不知道为什么我需要在方法 getId() 中使用 const 来修复该错误?谢谢
最佳答案
bool operator()(const Test& t1, const Test& t2)
您的运算符引用了const Test
对象。您只能通过对 const
限定类型的引用来调用 const
限定的成员函数。
set<Test>::iterator it = s.begin()
std::set
的元素是不可变的:您无法更改它们。因此,std::set
中的迭代器始终是 const
限定的对象类型。
关于c++ - 常量成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6039567/