Initializing a variable using default constructor [duplicate]

风流意气都作罢 提交于 2019-12-24 21:06:20

问题


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++


来源:https://stackoverflow.com/questions/29194418/initializing-a-variable-using-default-constructor

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