为什么C11’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.

很难证明是负面的,但在标准中根本没有明确的规定允许汽车在你的情况下.

但是,同样的规则意味着以下内容是有效的:

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++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录<future>future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...