gpt4 book ai didi

C++运算符==和隐式转换解析

转载 作者:太空狗 更新时间:2023-10-29 20:54:40 25 4
gpt4 key购买 nike

如果我有一个 struct A 定义为:

struct A {
const char *data;
operator const char * () const { return data; }
friend bool operator== (const A &s1, const char *s2)
{ return /* typical string comparison result */; }
};

而我写A{"hello"} == "test2"A::operator==被调用了吗?标准中的内容说明(以及为什么 A 不隐式转换为 const char *?)

"test2"== A{"hello"} 怎么样?在这种情况下,A 是否已转换?

编辑:如果 struct A 也有成员怎么办:

friend bool operator== (const char *s1, const A &s2)

最佳答案

当你做的时候

A{"hello"} == "test2"

我们对 operator== 执行重载决议。首先,我们通过名称查找找到可行的候选者 ([over.match.viable]):

operator==(A const&, const char*);    // yours
operator==(const char*, const char*); // built-in

接下来,我们确定哪个候选者具有最佳隐式转换序列。这是 [over.match.best] 中的第一个决胜局:

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then
(1.3) — for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that, [...]

两个运算符在第二个参数上都是完全匹配的。对于第一个参数,您的 operator== 是精确匹配,而内置的则需要用户定义的转换。精确匹配是最好的一种转换,而用户定义的是最差的 - 因此,您的转换顺序更好,成为最好的可行功能。

从广义上讲,A 不会隐式转换为 const char*,因为有更好的选择,但不一定如此。


当你这样做时:

"test2" == A{"hello"};

您的候选人不可行 - 没有从 const char*A const&(第一个参数)的隐式转换,因此唯一可行的候选人是内置的-与 const char* 相比,它需要用户定义的从 Aconst char* 的转换。

如果您希望调用您的A::operator==,您必须为operator==(const char*, A const&) 添加一个新的重载

关于C++运算符==和隐式转换解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38356069/

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