What's the differences between Test t; and Test t();? if Test is a class [duplicate]

血红的双手。 提交于 2019-12-17 18:29:52

问题


Possible Duplicate:
Why is there no call to the constructor?

I am using Visual studio 2012, Suppose Test is a class

class Test
{
};

When I create a new instance of Test, what's the difference of the following two ways?

way 1

Test t;

way 2

Test t();

I got this question in the code below, originally, I defined an instance of A in way 2, I got only one error because B does not provide an default constructor, but when I define it in way 1, I got an extra error.

class B
{
    B(int i){}
};

class A
{
    A(){}
    B b;
};

int main(void) 
{ 
    A a(); // define object a in way 2

    getchar() ; 
    return 0 ; 
} 

if I define a in way 1

A a;

I will got another error said

error C2248: 'A::A' : cannot access private member declared in class 'A'

So I guess there must be some differences between the two ways.


回答1:


Test t; defines a variable called t of type Test.

Test t(); declares a function called t that takes no parameters and returns a Test.




回答2:


What is the Difference between two declarations?

A a(); 

Declares a function and not an object. It is one of the Most vexing parse in C++.
It declares a function by the name a which takes no parameters and returns a type A.

A a;

Creates a object named a of the type A by calling its default constructor.

Why do you get the compilation error?

For a class default access specifier is private so You get the error because your class constructor is private and it cannot be called while creating the object with above syntax.



来源:https://stackoverflow.com/questions/12686298/whats-the-differences-between-test-t-and-test-t-if-test-is-a-class

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