gpt4 book ai didi

c++ - 为什么添加两个字符串文字不使用 operator+?

转载 作者:可可西里 更新时间:2023-11-01 16:09:53 25 4
gpt4 key购买 nike

编辑:我重新格式化了帖子以使其更清晰。

为什么这样做:

struct A {};

struct B {
B(A){}
};

void operator+(const B&, const B&) {}

int main()
{
A a1, a2;
a1 + a2;
}

这不是吗?

struct B {
B(const char*){}
};

void operator+(const B&, const B&) {} //error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'|

int main()
{
"Hello" + "world";
}

本质上,在第一个示例中,a1a2 都通过隐式转换转换为 B 对象,并使用 operator+( const B&, const B&) 添加。

根据这个例子,我希望 "Hello""world" 再次通过隐式转换为 B 对象构造函数,并使用operator+(const B&, const B&)相加。取而代之的是一个错误,它表明 C 风格的字符串不会尝试将用户定义的转换为 B 以便添加。为什么是这样?是否存在阻止这种情况发生的基本属性?

最佳答案

在您的第一个示例中,允许重载解析找到您的operator+:

[C++14: 13.3.1.2/2]: If either operand has a type that is a class or an enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator. [..]

[C++14: 13.3.2/1]: From the set of candidate functions constructed for a given context (13.3.1), a set of viable functions is chosen, from which the best function will be selected by comparing argument conversion sequences for the best fit (13.3.3). The selection of viable functions considers relationships between arguments and function parameters other than the ranking of conversion sequences.

[C++14: 13.3.2/2]: First, to be a viable function, a candidate function shall have enough parameters to agree in number with the arguments in the list.

  • If there are m arguments in the list, all candidate functions having exactly m parameters are viable.
  • [..]

[C++14: 13.3.2/3]: Second, for F to be a viable function, there shall exist for each argument an implicit conversion sequence (13.3.3.1) that converts that argument to the corresponding parameter of F. [..]

(您可以自己检查“隐式转换序列”的措辞,看看 operator+ 调用是允许的;规则过于冗长,无法保证在此处逐字复制。)

但是,在您的第二个示例中,重载解析受限于基本算术加法机制(未为 const char[N]const char* 定义的机制), 有效地禁止考虑任何 operator+ 函数:

[C++14: 13.3.1.2/1]: If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.

[C++14: 5.7/1]: [..] For addition, either both operands shall have arithmetic or unscoped enumeration type, or one operand shall be a pointer to a completely-defined object type and the other shall have integral or unscoped enumeration type. [..]

[C++14: 5.7/3]: The result of the binary + operator is the sum of the operands.

关于c++ - 为什么添加两个字符串文字不使用 operator+?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202400/

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