Eric Lippert 写了一篇关于 Why no var on fields? 的文章在 C# 中。我很好奇,我们能否在 C++0x 中做到这一点?例如。
struct mystruct_t
{
auto i = 0, d = 0.0, s = std::string("zero");
};
抱歉,我无法通过最新草稿得出答案。
谢谢,
最佳答案
遗憾的是你不能。该规范在 7.1.6.4/3 中说明并遵循
Otherwise, the type of the variable is deduced from its initializer. The name of the variable being declared shall not appear in the initializer expression. This use of auto is allowed when declaring variables in a block (6.3), in namespace scope (3.3.6), and in a for-init-statement (6.5.3).
The auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) or an iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), in a for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appears within the member-specification of a class definition (9.4.2).
A program that uses auto in a context not explicitly allowed in this section is ill-formed.
我不确定他们为什么禁止非静态数据成员使用 auto
,这会很方便。
关于c++ - 是否可以在 C++0x 中使用 auto 执行以下操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4466433/