gpt4 book ai didi

c++11 - 在 C++ 流中使用三元运算符可以吗?

转载 作者:行者123 更新时间:2023-12-02 04:10:42 25 4
gpt4 key购买 nike

以下代码:

#include <iostream>
using namespace std;
struct A{int number=10;};

int main()
{
A* a = new A();
cout<<"A val: "<< a==nullptr?"":a->number<<endl;
}

在 gcc 4.7 上用 c++11 编译给出:

error: invalid operands of types 'int' and '' to binary 'operator <<'

我不明白为什么,正确的方法是什么?我希望 null 检查尽可能短,因为我希望它们很常见。

最佳答案

首先:是的,您可以对 std::ostream 使用三元运算符,但注意运算符优先级。如果你打算这样做,你需要做这样的事情:

cout << "My name is: " << (my != nullptr ? my->name() : "don't know") << '\n';

换句话说,将三元表达式封装在括号中。

其次,第二个和第三个操作数必须可转换为同一类型。换句话说,您的示例将不起作用,因为如果 a 为空,您将尝试插入字符串文字 (""),或者插入实际数字 ( a->number,如果 a 不为 null,则为 int 类型。

第三,你需要修复语法。但是@quamrana 已经解决了这个问题。

关于c++11 - 在 C++ 流中使用三元运算符可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36894751/

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