这来自Herb Sutter的gotw3(http://www.gotw.ca/gotw/003.htm).
具有以下类别和FindAddr功能......
using std::string;
using std::list;
class Employee
{
public:
Employee(const string& n, const string& a) : name(n), addr(a) { }
string name;
string addr;
};
string FindAddr(const list<Employee>& l, const string& name)
{
string addr;
list<Employee>::const_iterator i = find(l.begin(), l.end(), name);
if (i != l.end()) {
addr = (*i).addr;
}
return addr;
}
Run Code Online (Sandbox Code Playgroud)
我收到编译错误,因为Employee类没有转换为字符串.我可以看到这样的转换不一定是明智的,但为了练习的目的,我添加了一个天真的转换:
string::string(const Employee& e)
{
return e.name;
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个错误:
gotw3.cc:17:9: error: C++ requires a type specifier for all declarations
string::string(const Employee& e)
~~~~~~ ^
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Jam*_*nze 10
两件事:首先,如果不修改类定义,则无法添加到现有类.如果你有一个你想要转换为std::string(或double与之相似)的类,你应该定义一个转换运算符:在你的情况下:
class Employee
{
// ...
operator std::string() const
{
return name; // Or whatever...
}
};
Run Code Online (Sandbox Code Playgroud)
其次,你的情况下的解决方案不是提供隐式转换,而是使用std::find_if适当的匹配器.在C++ 11中,这可以通过使用lambda来完成,但通常(在旧版本的C++中),您始终可以定义函数类型.对于这样的情况,一个类有一个自然的"键",我可能会添加一些成员类,类似于:
class Match : std::unary_function<Employee, bool>
{
std::string myName;
public:
explicit Match( std::string const& name )
: myName( name )
{
}
bool operator()( Employee const& toBeMatched ) const
{
return toBeMatched.name == myName;
}
};
Run Code Online (Sandbox Code Playgroud)
定义排序关系或密钥相等的其他功能类型也可能是有序的.