#include <atomic>
std::atomic<int> outside(1);
class A{
std::atomic<int> inside(1); // <--- why not allowed ?
};
error :
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'
最佳答案
类内初始化器不支持 (e)
初始化语法,因为设计它的委员会成员担心潜在的歧义(例如,众所周知的 T t(X ());
声明将是模棱两可的,并且不指定初始化但声明具有未命名参数的函数)。
你可以说
class A{
std::atomic<int> inside{1};
};
或者,可以在构造函数中传递一个默认值
class A {
A():inside(1) {}
std::atomic<int> inside;
};
关于c++ - 为什么允许在类外部指定默认值,但不允许在类内部指定默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12339072/