Is it a legal notation: Foo &foo = Bar;

蓝咒 提交于 2019-12-13 07:47:01

问题


struct Foo {};
struct Bar : Foo {};

Foo &foo = Bar; // without ()

I wonder, Is it a legal notation? And if it is legal, could you give some details? Something like, Why it's legal? Or, What is the origin of such a notation?

EDIT: I cannot compile this code. But I met a code like that and wanted to know whether such a notation is allowed (probably just my compiler doesn't support this notation). I'm having some uncertainty since the following notation is quite legal: Foo *pFoo = new Bar;


回答1:


  1. You cannot assign an class Name to a reference/object. It is neither syntactically valid nor does it make any sense.
  2. You cannot bind a reference to a temporary(rvalue), So following is illegal too:

    Foo &foo = Bar();

  3. You can bind a temporary(rvalue) to an const reference, So following is legal:

    const Foo &foo = Bar();

The C++ standard specifically allows the 3.




回答2:


It should be a compiler error.

g++: error: expected primary-expression before ';' token

Bar is a name of class and it cannot be assigned to reference / variable. Even with putting () it will not compile, unless you make foo a const Foo&.




回答3:


The code as presented is not legal because Bar is the name of a class, not a variable.

The following, however, is:

struct Foo {}
struct Bar : Foo {}

Bar fooBar;
Foo &foo = fooBar; // without ()

It is legal because Bar is a Foo, so you're just giving a different name to your variable fooBar.

Note however that foo, although an alias for fooBar, will interpret the location as a Foo object.

This means the following:

struct Foo { int x; };       //note semicolons after struct declaration
struct Bar : Foo { int y; };

Bar fooBar;
fooBar.y = 2;
fooBar.x = 3;
Foo &foo = fooBar;
int aux;
aux = foo.x; // aux == 3
aux = foo.y; // compile error



回答4:


You can't assign a value to a reference. So as already mentioned this is not legal regardless of the parentheses.



来源:https://stackoverflow.com/questions/7953484/is-it-a-legal-notation-foo-foo-bar

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