gpt4 book ai didi

c++ - 赋值运算符的 boolean 和字符串重载 (C++)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:58 24 4
gpt4 key购买 nike

我正在定义赋值运算符的多个重载,如下所示:

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");

问题:有人能告诉我为什么在 boolean 上下文中评估未转换的字符串文字吗?

最佳答案

C++ 标准在第 13.3 章定义了重载决议规则,在那里你会发现:

13.3.3.2 Ranking implicit conversion sequences [over.ics.rank]

2 When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1)

— a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and

— a user-defined conversion sequence (13.3.3.1.2) is a better conversion sequence than an ellipsis conversion sequence (13.3.3.1.3).

这意味着如果可用,编译器将更喜欢从字符串文字到 boolint 的标准转换序列。现在,哪些标准转换是相关的?在您的情况下,这两个是相关的:

4.2 Array-to-pointer conversion [conv.array]

1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

此转换将类型为 const char[N] 的字符串文字转换为 const char*。第二个是:

4.12 Boolean conversions [conv.bool]

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

这就是指针被转换为bool的原因。由于存在标准转换序列,因此不使用用户定义的到 std::string 的转换。

为了解决您的问题,我建议您添加另一个采用 const char* 的重载版本,并将调用转发到 const std::string& 重载。

关于c++ - 赋值运算符的 boolean 和字符串重载 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15032044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com