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

错误

prog.cpp:4:25: error: expected identifier before numeric constant
prog.cpp:4:25: error: expected ',' or '...' before numeric constant

在 VS11 中

C2059: syntax error : 'constant'
4

1 回答 1

8

类内初始化器不支持(e)初始化的语法,因为设计它的委员会成员担心潜在的歧义(例如,众所周知的T t(X());声明将是模棱两可的,并且没有指定初始化,但声明了一个带有未命名参数的函数)。

你可以说

class A{
    std::atomic<int> inside{1};
};

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

class A {
  A():inside(1) {}
  std::atomic<int> inside;
};
于 2012-09-09T12:31:59.897 回答