首页 > 解决方案 > 初始化和 ?: 运算符

问题描述

此代码在 Visual Studio 2019 中失败:

// struct D2D1_COLOR_F { float r,g,b,a};

bool x = ...;
D2D1_COLOR_F col = x ? { 0, 0, 0, 1 } : { 1, 1, 1, 1 };

正如我尝试的那样,它在 g++ 中也失败了。这是编译器限制还是我在语法中遗漏了什么?

没有?:它的工作:

if (x)
   col = {0,0,0,1};
else
   col = {1,1,1,1};

它也可以通过显式使用构造函数来工作:

D2D1_COLOR_F col = x ? D2D1_COLOR_F{ 0, 0, 0, 1 } : D2D1_COLOR_F{ 1, 1, 1, 1 };

它显示语法错误:

1>(20,25): error C2059: syntax error: '{'
1>(20,25): error C2143: syntax error: missing ';' before '{'
1>(20,38): error C2143: syntax error: missing ';' before '}'
1>(20,40): error C2059: syntax error: ':'
1>(22,9): error C2143: syntax error: missing ';' before '-='
1>(22,9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

标签: c++visual-studiog++

解决方案


推荐阅读