为什么允许在类之外指定默认值但不在其中?

3 c++ constructor initialization default-value c++11

#include <atomic>
std::atomic<int> outside(1);
class A{
  std::atomic<int> inside(1);  // <--- why not allowed ?
};
Run Code Online (Sandbox Code Playgroud)

错误:

prog.cpp:4:25: error: expected identifier before numeric constant
prog.cpp:4:25: error: expected ',' or '...' before numeric constant
Run Code Online (Sandbox Code Playgroud)

在VS11

C2059: syntax error : 'constant'
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 6

类内初始值设定项不支持(e)初始化语法,因为设计它的委员会成员担心潜在的歧义(例如,众所周知的T t(X());声明将是不明确的,并且不指定初始化但声明具有未命名参数的函数).

你可以说

class A{
    std::atomic<int> inside{1};
};
Run Code Online (Sandbox Code Playgroud)

或者,可以在构造函数中传递默认值

class A {
  A():inside(1) {}
  std::atomic<int> inside;
};
Run Code Online (Sandbox Code Playgroud)

  • 虽然正确的ATM gcc和VC11都不支持`{1}`:(.+ 1 (2认同)