我的程序结构类似于:
class A {
private:
std::set<B> members;
public:
void func(const C& arg) {
std::set<B>::iterator iter = members.find(a);
if(iter != members.end()) {
iter->check(arg);
}
}
}
class B {
private:
std::deque<C> writers;
public:
void check(const C& arg) {
if(std::find(writers.begin(), writers.end, arg) != writers.end()) {
/* Code */
}
}
}
class C {
private:
int id;
public:
bool operator==(const C& arg) {
return arg.id == this->id;
}
}
当我编译它时,我收到以下错误消息:
no matching function for call to ‘B::check(const C&) const’
note: candidates are: void B::check(const C&) <near match>
如果我将 check()
声明为 const
,那么编译器会抛出一个错误,要求 C 类中的重载运算符 ==
是声明为 const
。我不知道将重载运算符设为 const
是否正确。 (我试过一次,据我所知也有一些错误)。
我已经尝试解决这个问题超过五天了,但仍然没有任何线索。
最佳答案
首先,operator==
应该是const
。它不会修改数据,也不应该修改数据,除非您想混淆您的用户。一般来说,每个不需要修改对象状态的函数都应该是 const
以提供最大的灵 active (即允许通过常量引用进行调用)。
同样可以应用于B::check
,如果它只是测试而不是修改,那么它应该是const
。并且通过 A::func
中的扩展,如果它不需要修改那么它应该是 const。
错误信息在不同的编译器中会略有不同。在您的情况下,编译器执行了重载解析,但没有找到与它提示的调用匹配的内容:
no matching function for call to ‘B::check(const C&) const’
note: candidates are: void B::check(const C&)
这表示它看到了您的成员但丢弃了它,因为它需要一个带有 const
标记的成员函数。在其他编译器中,错误消息将包含以下内容:calling void B::check(const C&)
discards qualifiers 这有点复杂,并试图说明在 const 引用上调用非常量成员函数需要忽略 const
限定符。
关于c++ - 在非常量函数中使用 const_iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12625271/