class Test
{
private:
int v;
public:
Test(int h)
{
v = h;
}
int getV()
{
return v;
}
bool operator < (const Test& b) const
{
return v < b.v;
}
};
int main()
{
set <Test> st;
for(int i = 1; i <= 10; i++)
{
Test t(i);
st.insert(t);
}
for(set<Test>::iterator it = st.begin(); it != st.end(); it++)
{
cout << (*it).getV() << endl;
//Test it2 = *it;
//cout << it2.getV() << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这将是
|错误:将'const Test'作为'int Test :: getV()'的'this'参数传递,丢弃限定符[-fpermissive] |
但如果我使用Test it2 = *it; cout << it2.getV() << endl;,它会很好用.为什么它使用'const Test'这个词以及为什么代码不能工作?
std::set迭代器返回const引用,因为sets已排序,如果更改集合中对象的值,则它可能位于新值的错误位置.这可能会使对象无法找到并且更糟.
当你这样做
Test it2 = *it;
Run Code Online (Sandbox Code Playgroud)
您正在复制该对象,您可以根据需要修改该副本.你不能通过set修改副本搞砸了.
问题是您的getV()方法没有正确的const限定.它应该是:
int getV() const
{
return v;
}
Run Code Online (Sandbox Code Playgroud)
然后第一个代码将编译并正常工作.
如果没有在正确的地方应用const,通常会导致这类问题.您应该正确地应用const限定.