2017-02-27 160 views
0
#include<iostream> 
using namespace std; 
class test 
{ 
    public: 
    int a,b; 

    test() 
    { 
     cout<<"default construictor"; 

    } 
    test(int x,int y):a(x),b(y){ 

     cout<<"parmetrized constructor"; 
    } 

}; 
int main() 
{ 

    test t; 
    cout<<t.a; 
    //t=(2,3);->gives error 
    t={2,3}; //calls paramterized constructor 
    cout<<t.a; 
} 

输出: - 默认construictor4196576parmetrized constructor2括号VS大括号

为什么在上面的例子中的情况下,参数的构造函数(即使默认构造函数已经调用。)被称为在{案例},而不是在()

+0

你使用C++ 11吗? – taskinoor

回答

4

我添加了一些额外的代码来显示实际发生的事情。

#include<iostream> 
using namespace std; 

class test 
{ 
    public: 
    int a,b; 

    test() 
    { 
     cout << "default constructor" << endl; 
    } 

    ~test() 
    { 
     cout << "destructor" << endl; 
    } 

    test(int x,int y):a(x),b(y) 
    { 
     cout << "parameterized constructor" << endl; 
    } 

    test& operator=(const test& rhs) 
    { 
     a = rhs.a; 
     b = rhs.b; 
     cout << "assignment operator" << endl; 
     return *this; 
    } 

}; 

int main() 
{ 

    test t; 
    cout << t.a << endl; 
    //t=(2,3);->gives error 
    t={2,3}; //calls parameterized constructor 
    cout << t.a << endl; 
} 

输出:

default constructor 
4197760 
parameterized constructor 
assignment operator 
destructor 
2 
destructor 

所以声明t={2,3};使用参数的构造函数实际上构造一个新的test对象,调用赋值运算符设置t到等于新的临时test对象,然后摧毁临时对象test。这相当于声明t=test(2,3)

+0

为什么在t =(2,3)的情况下不能在这里工作? – unixlover

+0

因为'(2,3)'不是有效的C++代码,'{2,3}'是一个列表。看到@Aldwin Cheung建议的C++书 – xander

4

使用

test t(2,3); 

代替

test t; 
t=(2,3); 

由于括号在对象声明之后使用。

+0

但是在这种情况下t = {2,3}如何工作? – unixlover