c++ - 这是什么疯狂的 C++11 语法 ==> struct : bar {} foo {};?

标签 c++ c++11

这在 C++11 中可能意味着什么?

struct : bar {} foo {};

最佳答案

首先,我们将采用标准抽象 UDT(用户定义类型):

struct foo { virtual void f() = 0; }; // normal abstract type
foo obj;
// error: cannot declare variable 'obj' to be of abstract type 'foo'

我们还记得,我们可以在定义 UDT 的同时实例化它:

struct foo { foo() { cout << "!"; } };          // just a definition

struct foo { foo() { cout << "!"; } } instance; // so much more
// Output: "!"

让我们结合示例,回想一下我们可以定义一个 没有名称的 UDT:

struct { virtual void f() = 0; } instance; // unnamed abstract type
// error: cannot declare variable 'instance' to be of abstract type '<anonymous struct>'

我们不再需要关于匿名 UDT 的证明,所以我们可以失去纯虚函数。同样将 instance 重命名为 foo,我们得到了:

struct {} foo;

越来越近了。


现在,如果这个匿名 UDT 是从某个基础派生出来的呢?

struct bar {};       // base UDT
struct : bar {} foo; // anonymous derived UDT, and instance thereof

最后,C++11 引入了扩展的初始化器,这样我们就可以做这样令人困惑的事情:

int x{0};

还有这个:

int x{};

最后,这个:

struct : bar {} foo {};

这是一个从 bar 派生的未命名结构体,实例化为 foo 并带有一个空白初始值设定项。

关于c++ - 这是什么疯狂的 C++11 语法 ==> struct : bar {} foo {};?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7067793/

相关文章:

c++ - 使用并行编程 C++ 计算/访问 vector

c++ - GotW #47 是不是错了一半?

c++ - BOOST_FOREACH 与 for 循环

c++ - 使用 promise 和 future 将值从子线程传递给主线程

c++ - 在 C++ 中使用 fifo(阻塞读取)

c++ - 二数符号四种情况的调理

c++ - 类型转换 NULL 的现有返回可以安全地与较新的 nullptr 进行比较吗?

c++ - 在 C++ 中初始化一个 std::bitset 数组

c++ - 使用 std::function 时如何解决此 <unresolved overloaded function type> 错误?

c++ - 关于在不调用复制构造函数的情况下返回 STL 容器数据成员