【发布时间】:2011-10-27 10:09:12
【问题描述】:
这在 C++11 中可能意味着什么?
struct : bar {} foo {};
【问题讨论】:
-
有趣,你觉得它有什么用吗?我想这是生成强类型(标记类型)单个实例的技巧。
-
@alfC:不是特别有用,没有
这在 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 并带有一个空白初始值设定项。
【讨论】:
这定义了:
bar公开派生
anonymously) 只定义了从 bar 派生的内容
struct : bar {} foo {};
【讨论】: