【问题标题】:Why specifying the default value outside of a class is allowed but not inside it?为什么允许在类之外指定默认值,但不允许在类内指定默认值?
【发布时间】:2012-09-02 13:47:55
【问题描述】:
#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'

【问题讨论】:

  • 尝试里面 = std::atomic(0);
  • 我认为课堂内的() 存在历史问题。你试过=而不是大括号吗?
  • @iammilind 猜猜看。它在外面有效,但在里面无效.....

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


【解决方案1】:

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

你可以说

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

也可以在构造函数中传递默认值

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

【讨论】:

  • 虽然 gcc 和 VC11 的正确 ATM 不支持 {1} :(.+1
  • Clang 3.0 及更高版本支持非静态数据成员初始化器 (N2756)。
  • @MatthieuM。我在 windows 上 :(。我最喜欢的 IDE 是 VS,我喜欢 clang,但它不支持 windows
  • @acidzombie24:我能理解VS(尤其是它的调试器)的吸引力。至于 Clang 中的 Windows 支持,它正在向前发展,但是是的,不幸的是,它仍然落后。就个人而言(家里也有一台 Windows 计算机),我在共享文件夹上使用代码块进行编辑......我有一个 Ubuntu VM 来编译/运行我的程序:)
  • 这是 C++11 语法,它还没有进入许多编译器。
猜你喜欢
  • 2020-12-02
  • 2014-10-11
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
相关资源
最近更新 更多