Co to za szalona składnia C++11 = = > struct: bar {} foo {};?
Co to może oznaczać w C++11?
struct : bar {} foo {};
168
Author: Tony Delroy, 2011-08-15
2 answers
Najpierw weźmiemy Bog-standard abstract UDT (typ zdefiniowany przez Użytkownika):
struct foo { virtual void f() = 0; }; // normal abstract type
foo obj;
// error: cannot declare variable 'obj' to be of abstract type 'foo'
Przypomnijmy również, że możemy utworzyć instancję UDT w tym samym czasie, w którym ją zdefiniujemy:
struct foo { foo() { cout << "!"; } }; // just a definition
struct foo { foo() { cout << "!"; } } instance; // so much more
// Output: "!"
Połączmy przykłady i Przypomnijmy, że możemy zdefiniować UDT, który ma bez nazwy :
struct { virtual void f() = 0; } instance; // unnamed abstract type
// error: cannot declare variable 'instance' to be of abstract type '<anonymous struct>'
Nie potrzebujemy już dowodu o anonimowym UDT, więc możemy stracić czystą funkcję wirtualną. Również zmiana nazwy instance
na foo
, zostaje nam:
struct {} foo;
Getting blisko.
A gdyby ten anonimowy UDT wywodził się z jakiejś bazy?
struct bar {}; // base UDT
struct : bar {} foo; // anonymous derived UDT, and instance thereof
Wreszcie, C++11 wprowadza rozszerzone inicjalizatory, takie, że możemy robić mylące rzeczy takie jak:
int x{0};
I to:
int x{};
I wreszcie to:
struct : bar {} foo {};
Jest to nienazwana struktura pochodząca z paska, utworzona jako foo z pustym inicjalizatorem.
262
Author: Lightness Races in Orbit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-02 15:31:24
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-02 15:31:24
To definiuje:
- an anonymous struct,
- która pochodzi z
bar
- który (
anonymously
) definiuje nic innego jak to, z czego pochodzibar
- i w końcu powstaje instancja o nazwie "foo",
- z pustą listą inicjalizacyjną
struct : bar {} foo {};
106
Author: Frunsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-05 15:43:47
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-05 15:43:47