2017-02-27 163 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