Initializing a variable using default constructor

2019-08-28 00:56发布

问题:

This question already has an answer here:

  • Default constructor with empty brackets 9 answers

I'm pretty new to c++, i'm now trying to learn all the basics, I know when default constructors are called, but when i tried different syntax it doesn't work like i expected.

Look at the following code:

class a;
class b();
class c(NULL);

'class' is a class i created with default constructor, for a and c everything works well, but for b it just won't recognize the variable as a class member.

As i see it b and c are basically the same, what's wrong than? Thanks!

回答1:

Don't name your class "class", as it is a reserved name.

As for C++, if the constructor takes no parameters, you instantiate it using

Foo a;   // note, if you are using c++11, you can do Foo a{};

As opposed to:

Foo b();

Which actually does something totally unexpected*, and declares a function named b that returns a Foo instance.

As for Foo c(null), it won't compile as there is no default constructor that takes an argument.


* It is referred to as "the most vexing parse", though I find that to be an exaggeration. It can certainly catch you by surprise, but just knowing that you can declare a function prototype inside a function, should be enough to remove the "vexing" aspect.

In other words int getMyInt(); is obviously a function prototype when placed outside any function definitions. However, since this is also the case when inside a function definition, int getMyInt(); doesn't do anything it wouldn't normally do... which is to define a function prototype getMyInt that returns an integer.



回答2:

b is interpreted as a declaration of a function taking no arguments and returning an object of type class.

This is known as the most vexing parse. Edit: This is not the most vexing parse.



回答3:

you meant something like this? NULL represents 0, you know. void means no data.

class Cl_Test
{
private:
    int m_a;
public:
    Cl_Test(int in_a= -1) { m_a= in_a; }
};

int main(int argc, char** argv) {
    Cl_Test a;
    Cl_Test b();
    Cl_Test c(void);
    return 0; }

edit:

my mistakes:

  • the "variable" b: It's not a variable, it's a function declaration
  • one should not pass a void as an argument in C/C++