c++ - 为什么 C++11 'auto' 关键字对静态成员不起作用?

标签 c++ c++11 auto

class Foo {
 public:
  static const char *constant_string;
};

auto Foo::constant_string = "foo";

int main(void) {
};

编译:gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 像这样:

gcc -std=c++0x ./foo.cc 
./foo.cc:6:11: error: conflicting declaration ‘auto Foo::constant_string’
./foo.cc:3:22: error: ‘Foo::constant_string’ has a previous declaration as ‘const char* Foo::constant_string’
./foo.cc:6:11: error: declaration of ‘const char* Foo::constant_string’ outside of class is not definition [-fpermissive]

这是 auto 关键字的预期行为,还是 gcc+ 中的错误

最佳答案

语言不允许:

[C++11: 7.1.6.4]:

1 The auto type-specifier signifies that the type of a variable being declared shall be deduced from its initializer or that a function declarator shall include a trailing-return-type.

2 The auto type-specifier may appear with a function declarator with a trailing-return-type (8.3.5) in any context where such a declarator is valid.

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). auto shall appear as one of the decl-specifiers in the decl-specifier-seq and the decl-specifier-seq shall be followed by one or more init-declarators, each of which shall have a non-empty initializer.

4 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).

5 A program that uses auto in a context not explicitly allowed in this section is ill-formed.

很难证明是否定的,但标准中根本没有明确的规则允许 auto 在您的情况下。

但是,相同的规则意味着以下有效的:

struct Foo {
   static constexpr auto constant_string = "foo";
};

int main() {}

(注意 Foo::constant_string 的类型是 char const* const 而不是 char const[3]; this is an effect of using auto .)

关于c++ - 为什么 C++11 'auto' 关键字对静态成员不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14285198/

相关文章:

c++ - 如何在 for 循环中声明第二个迭代器?

c++ - K&R 样式函数定义使用 g++ 编译

c++ - 计算二叉树中具有特定数量子节点的节点?

c++ - 使用正则表达式进行全词匹配

c++ - 方法定义推导的类型与声明不匹配

c++ - gtkmm 中的异形窗口

c++ - 使用 std::transform 制作一对 vector

C++11 正则表达式与字符串不匹配

c++ - lambda 中的递归调用 (C++11)

C++ 确定 auto 的类型并传递给函数模板