为什么在条件运算符(?:)中,第二个和第三个操作数必须具有相同的类型? [英] Why in conditional operator (?:), second and third operands must have the same type?

查看:237
本文介绍了为什么在条件运算符(?:)中,第二个和第三个操作数必须具有相同的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在条件运算符(?:)中,第二个和第三个操作数必须具有相同的类型?

Why in conditional operator(?:), second and third operands must have the same type?

我的代码如下:

#include <iostream>
using std::cout;

int main()
{
    int a=2, b=3;
    cout << ( a>b ? "a is greater\n" : b );  /* expression ONE */
    a>b? "a is greater\n" : b;               /* expression TWO */

    return 0;
}

使用g ++进行编译时,会发出错误消息:

When compile it using g++, it issue an error:

main.cpp:7:36: error: operands to ?: have different types ‘const char*’ and ‘int’
main.cpp:8:28: error: operands to ?: have different types ‘const char*’ and ‘int’

我想知道为什么它们必须具有相同的类型?

I wonder why they must have the same type?

(1)我认为,如果(a&b; b)为true,则表达式(a> b?"a更大\ n:b)将返回" a大于\ n" cout<<"a大于\ n" 将输出该字符串;
否则表达式将返回 b cout<<b 将输出b的值.

(1) In my opinion, if (a>b) is true, then the expression ( a>b ? "a is greater\n" : b )will return "a is greater\n" and cout << "a is greater\n" will output that string;
otherwise the expression will return b, and cout << b will output the value of b.

但是,不幸的是,事实并非如此.为什么?

But, unfortunately it is not like this. WHY?

(2)第二个表达式出现相同的错误.

(2) The second expression gets the same error.

PS:我知道,是标准人员说必须是这样,但是,为什么标准要这样说?

推荐答案

您应该尝试分解正在理解的内容:

You should try to decompose what's happening to understand:

cout << ( a>b ? "a is greater\n" : b );

这翻译成:

operator<<(cout, ( a>b ? "a is greater\n" : b ));

在那个阶段,编译器必须选择以下重载之一:

At that stage the compiler must choose one of the following overloads:

ostream& operator<<(ostream&, int);
ostream& operator<<(ostream&, const char*);

但这不是因为三元运算符的结果类型未知(仅在运行时).

But it can't because the type of result of the ternary operator is not known yet (only at runtime).

为使事情更清楚,请这样考虑:

To make things clearer think like this:

 auto c = a>b ? "test" : 0;

c 的类型是什么?无法在编译时决定.C ++是静态类型语言.所有类型都必须在编译时知道.

What would be the type of c ? It can't be decided at compile time. C++ is a statically typed language. All types must be known at compile time.

您正在考虑 a吗?b:c 通过以下方式:

You are thinking of a ? b : c in the following way:

if (a)
    b;
else
    c;

实际上是这样的:

if (a)
    return b;
else
    return c;

这篇关于为什么在条件运算符(?:)中,第二个和第三个操作数必须具有相同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆