【问题标题】:`public` access qualifier and `const`ness. `-Wuninitialized``public` 访问限定符和`const`ness。 `-Wuninitialized`
【发布时间】:2013-03-14 19:29:21
【问题描述】:
class Foo
{
    public:
        const int x;
};

class Bar
{
    private:
        const int x;
};

输出:

test.cpp:10:13: warning: non-static const member ‘const int Bar::x’ in class without a constructor [-Wuninitialized]

为什么Bar 会产生警告而Foo 不会(显然是因为访问限定符,但逻辑是什么?)。

【问题讨论】:

  • 这是整个程序吗?
  • 这是我编译的完整 MWE。

标签: c++ warnings member access-specifier


【解决方案1】:

有了这些定义,由于Foo::x 是公开的,您可以有效地实例化Foo,如下所示:

Foo f { 0 }; // C++11

Foo f = { 0 };

Bar 不能这样做。

【讨论】:

  • 那一些不寻常的语法(至少对我来说)。能否提供资源。
  • @aiao 第一个是 C++11 中的新语法(通常被错误地命名为 uniform initialization),与第二个等价。在这种情况下,它们都执行聚合初始化(C++11 的第 8.5.1 节)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 2020-09-26
  • 2011-04-10
相关资源
最近更新 更多