What is this crazy C++11 syntax ==> struct : bar {} foo {};?

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

What could this possibly mean in C++11?

struct : bar {} foo {};

回答1:

First, we'll take a bog-standard abstract UDT (User-Defined Type):

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

Let's also recall that we can instantiate the UDT at the same time that we define it:

struct foo { foo() { cout 

Let's combine the examples, and recall that we can define a UDT that has no name:

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

We don't need the proof about the anonymous UDT any more, so we can lose the pure virtual function. Also renaming instance to foo, we're left with:

struct {} foo;

Getting close.


Now, what if this anonymous UDT were to derive from some base?

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

Finally, C++11 introduces extended initialisers, such that we can do confusing things like this:

int x{0};

And this:

int x{};

And, finally, this:

struct : bar {} foo {};

This is an unnamed struct deriving from bar, instantiated as foo with a blank initializer.



回答2:

This defines:

  • an anonymous struct,
  • which is derived publicly from bar
  • which (anonymously) defines nothing else but what it derived from bar
  • and finally, an instance, called "foo" is created,
  • with an empty initializer list

struct : bar {} foo {};


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!