C++ spooky constructor [duplicate]

最后都变了- 提交于 2019-11-30 23:14:44

问题


Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

Lets have this code

class Foo {
  Foo(int) { }
};

Then we have there results:

int main() {
  Foo f1 = Foo(5); // 1: OK, explicit call
  Foo f2(5); // 2: OK, implicit call
  Foo f3(); // 3: no error, "f3 is a non-class type Foo()", how so?
  Foo f4(f1); // 4: OK, implicit call to default copy constructor
  Foo f5; // 5: expected error: empty constructor missing
}

Can you explain what's happening in case 3?


回答1:


Foo f3(); declares a function called f3, with a return type of Foo.




回答2:


The third line is parsed as declaring a function that takes no argument and returns a Foo.




回答3:


C++ has a rule that if a statement can be interpreted as a function declaration, it is interpreted in this way.

Hence the syntax Foo f3(); actually declares a function which takes no arguments and returns Foo. Work this around by writing Foo f3;, it will call the default constructor too (if there is one, of course).




回答4:


  • f1 invokes the copy constructor after an explicit call, you were wrong on this one
  • f2 is an explicit constructor call // you were wrong here too
  • f3 declares a function
  • f4 is again the copy constructor, like f1 // you're right here
  • f5 would calls the default constructor // you're right here again



回答5:


This isn't what you think it is:

 Foo f3();

You may think this is an explicit call of the default constructor, but it's not. It's actually a declaration of a function named f3 which takes no parameters and returns a Foo by value.

That this is parsed as a function declaration rather than a constructor call is known as the Most Vexing Parse.




回答6:


You've defined a function called f3 that returns a foo in case 3. In case 5, you have no default constructor defined, so you get an error.



来源:https://stackoverflow.com/questions/8475851/c-spooky-constructor

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