简体   繁体   中英

Strange behavior in constructor

I have a class made up of several fields, and I have several constructors. I also have a constructor that doesn't take any parameters, but when I try to use it:

int main {
    A a;
}

The compiler generates an error, while if I use it like this:

int main {
    A a();
}

It's ok. What's that?

Thank you

The first main uses A's default constructor. The second one declares a function that takes no parameters and returns an A by value, which probably isn't what you intend.

So what does the definition of A look like and what is the error that the compiler generates?

Oh, and you need to provide a parameter list in the declaration of main: int main() { //... , not int main { //...

By OK you mean it compiles or that it works? The line of code:

   A a();

is a declaration (or prototype) of a function named a that takes no parameters and returns an object of type A .

I think for anyone to have a chance to help you with your real problem you'll need to post at least the declaration for class A .

Charles and Michael Burr both identified that the second declaration was in fact a function prototype and not an instantiation of A .

As for possible reasons why your first code snippet did not work, you would get a compilation error in this situation when:

  1. Class A inherits from a base class that has no default constructor; OR
  2. Class A contains objects of types that have no default constructor; OR
  3. Class A contains reference members;

AND

You have provided a default constructor which omits one or more of these subobjects from its initialiser list.

All of these subobjects need some way to be initialised, and the default constructor produced by the compiler won't do it. Note that in all cases you need to initialise them in the initialiser list , not the body of the constructor.

你可能都是对的,我有类的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM