为什么声明 `operator bool() const` 成员会重载 [] 运算符? [重复]

问题描述 投票:0回答:1

为什么这段代码可以编译?由于没有声明

operator[]
,我预计它会失败。
operator[]
的定义从何而来?

struct Test {
    operator bool() const {
        return true;
    }
};

int main(int argc, char** argv) {
    Test test;

    if (test["wut"])
        cout << "Success (test[\"wut\"])\n";
}
c++ operators
1个回答
-1
投票

运算符来自内置下标运算符,它将表达式

A[B]
视为
*(A + B)

在这些情况下,

test
通过
0
方法隐式转换为整数类型的值
1
operator bool()
(对于所有这些情况都是
1
)。

这导致评估

*(1 + "wut")
=>
'u'
,然后导致
if
条件通过,因为
'u'
是一个非零值。同样,以下条件也将通过
if ("wut"[test])
,因为这解析为
"wut"[1]
=>
*("wut" + 1)
=>
*("ut")
=>
'u'

将您的成员声明为

explicit operator bool()
以防止您的类型被隐式转换为其他整数类型。

© www.soinside.com 2019 - 2024. All rights reserved.