我将定义多个重载的赋值运算符,如下所示:
Foo.h
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");
问题:有人能告诉我为什么未转换的字符串文字在布尔上下文中被评估吗?
Foo
是构造函数还是其他任何方法,方法签名Foo(std::string&)
和Foo(char*)
是非常不同的。所以,我现在意识到我理解上的差距实际上已经超越了我在发布问题时看到的赋值运算符的情况。 - DavidRR