小编dib*_*dib的帖子

C++:三元运算符(条件运算符)及其隐式类型转换规则

是否有三元运算符参数的隐式类型转换规则?

三元运算符总是需要返回相同的类型.此类型仅由第二个和第三个参数(1st ? 2nd : 3rd)确定,因此两个参数都转换为此类型.这种类型是如何确定的?

更具体地说,我测试了一个例子:

class pointclass
{
    pointclass();

    pointclass( int i );    // (pointclass)(int)
    operator bool() const;  // (bool)(pointclass)
};
Run Code Online (Sandbox Code Playgroud)

我有一个类(pointclass),它使从隐式转换intpointclass和从隐式转换pointclassbool.

int i;
pointclass p;
bool b;

b ? p : i;  // (bool) ? (int)(bool)(pointclass) : (int)
b ? i : p;  // (bool) ? (int) : (int)(bool)(pointclass)
Run Code Online (Sandbox Code Playgroud)

使用三元运算符,我比较pointclassint.编译器使用从隐式转换pointclassbool,然后从标准转换boolint.无论我是否交换第二和第三个参数,这都已完成.为什么不转换int为 …

c++ types implicit ternary

9
推荐指数
1
解决办法
1556
查看次数

标签 统计

c++ ×1

implicit ×1

ternary ×1

types ×1