【发布时间】:2012-06-27 14:57:16
【问题描述】:
我有以下代码:
class Employee {
friend string FindAddr( list<Employee> lst,string name );
public:
Employee(const string& s){ cout << "Employee CTOR" << endl;}
bool operator==( Employee& e) {
return e.name == name;
}
private:
string name;
string addr;
};
string FindAddr( list<Employee> lst, string name ) {
string result = "";
for( list<Employee>::iterator itr = lst.begin(); itr != lst.end(); itr++ ) {
if ( *itr == name ) { // Problematic code
return (*itr).addr;
}
}
return result;
}
据我了解,有问题的行if ( *itr == name ) 应遵循以下步骤:
- 在
Employee类上识别它是operator==。 - 试图确定是否存在从
string name到Employee的转换,以便操作员可以工作。 - 在对象
string name上隐式调用构造函数Employee(const string& s)。 - 继续
operator==。
但是,这一行在编译时给我带来了麻烦:
Invalid operands to binary expression ('Employee' and 'string' (aka 'basic_string<char>'))
即使我显式调用构造函数:
if ( *itr == Employee::Employee(name) )
我得到同样的错误。
这令人困惑。我很难理解隐式构造函数调用何时起作用(以及为什么即使我显式调用构造函数代码也不起作用)。
谢谢!
【问题讨论】:
-
这正是您应该在
operator==中使用const引用的原因。 -
提示:临时变量不能绑定到非常量引用。
-
因为它没有改变状态,所以成员函数也应该是
const,这样它就可以在const对象上调用。
标签: c++ operators implicit-conversion implicit