我正在定义赋值运算符的多个重载,如下所示:
Foo.h
class Foo
{
private:
bool my_bool;
int my_int;
std::string my_string;
public:
Foo& operator= (bool value);
Foo& operator= (int value);
Foo& operator= (const std::string& value);
};
Foo.cpp
// Assignment Operators.
Foo& Foo::operator= (bool value) {my_bool = value; return *this;}
Foo& Foo::operator= (int value) {my_int = value; return *this;}
Foo& Foo::operator= (const std::string& value) {my_string = value; return *this;}
这是我的 main.cpp(请参阅标记为 的评论SURPRISE
):
Foo boolFoo;
Foo intFoo;
Foo stringFoo;
// Reassign values via appropriate assignment operator.
boolFoo = true; // works...assigned as bool
intFoo = 42; // works...assigned as int
stringFoo = "i_am_a_string"; // SURPRISE...assigned as bool, not string
std::string s = "i_am_a_string";
stringFoo = s; // works...assigned as string
// works...but awkward
stringFoo = static_cast<std::string>("i_am_a_string");
问题:有人能告诉我为什么在布尔上下文中评估未转换的字符串文字吗?