c++ - 为什么允许在类外部指定默认值,但不允许在类内部指定默认值?

标签 c++ constructor c++11 initialization default-value

#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/

相关文章:

c++ - 使用 STL 输出二进制缓冲区

C++如何使模板化代码更清晰

c++ - C++11中根据类型要求特化类模板成员函数

c++ - A'无法解决

c++ - 在不处理它的应用程序中使用 unicode/UTF8 处理/清理用户输入

c++ - 当模板类的输入输出类型不同时如何处理构造函数

java - 当构造函数具有类的类型时,这意味着什么?

c++ - 构造函数如何工作

c++ - 如何一次将多个整数传递给一个 vector ?

c++ - auto && outside range-for