这是无效的 C++ 吗?

发布于 2024-10-29 16:52:50 字数 360 浏览 6 评论 0原文

struct HybridExpression {
    RawExpressionElement *ree;
    ExpressionNode *en;
};    

vector<HybridExpression> hexpression;

hexpression.insert(hexpression.begin() + starti, 
        (HybridExpression) {NULL, en}); 

gcc 构建时不会发出警告,但 Visual Studio 2010 甚至不会编译它。

它不喜欢这一点:(HybridExpression) {NULL, en}

struct HybridExpression {
    RawExpressionElement *ree;
    ExpressionNode *en;
};    

vector<HybridExpression> hexpression;

hexpression.insert(hexpression.begin() + starti, 
        (HybridExpression) {NULL, en}); 

gcc builds without warning but visual studio 2010 wont even compile it.

It doesnt like this bit: (HybridExpression) {NULL, en}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眼趣 2024-11-05 16:52:50

这是使用 C 编程语言中未包含在 C++ 中的一部分,称为“复合文字”。 g++ -ansi 会对此进行诊断,并表示

警告:ISO C++ 禁止复合文字

这不是 C++0x 的一部分。

C++0x 兼容语法是

hexpression.insert(hexpression.begin() + starti, HybridExpression{NULL, en});

引用 C99 标准,第 6.5.2.5 段:

由括号组成的后缀表达式
类型名称,后跟大括号括起来的初始值设定项列表
是一个复合文字。它提供了一个未命名的对象,其
值由初始化列表给出。

This is using a part of the C programming language that is not included in C++, it's called "compound literal". g++ -ansi will diagnose this, saying

warning: ISO C++ forbids compound-literals

This is not a part of C++0x.

The C++0x compatible syntax would have been

hexpression.insert(hexpression.begin() + starti, HybridExpression{NULL, en});

To quote the C99 standard, paragraph 6.5.2.5:

A postfix expression that consists of a parenthesized
type name followed by a brace-enclosed list of initializers
is a compound literal. It provides an unnamed object whose
value is given by the initializer list.

阳光①夏 2024-11-05 16:52:50

根据 http://gcc.gnu .org/onlinedocs/gcc-4.1.2/gcc/C_002b_002b-Extensions.html#C_002b_002b-Extensions,您可以在使用 GCC 编译的 C++ 程序中使用 C 扩展(包括 C99 的东西)。

复合文字 是扩展名你实际上正在使用。

According to http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/C_002b_002b-Extensions.html#C_002b_002b-Extensions, you can use C extensions (including C99 stuff) in C++ programs compiled with GCC.

Compound literals is the extension you're actually using.

雨巷深深 2024-11-05 16:52:50

这在当前标准中不是有效的 C++。我认为 GCC 允许这样做是因为有特定于 GCC 的编译器扩展。

This is not valid C++ in the current Standard. I think GCC allows it because of a GCC-specific compiler extension.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文