2016-07-19 150 views
2

我想執行以下代碼:有多個構造函數初始化成員變量調用

#include <iostream> 
using namespace std; 

class ABC { 
private: 
    int x, y; 
public: 
    ABC(){ 
     cout << "Default constructor called!" << endl; 
     ABC(2, 3); 
     cout << x << " " << y << endl; 
    } 
    ABC(int i, int j){ 
     cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl; 
     x = i; 
     y = j; 
     cout << x << " " << y << endl; 
    } 
}; 

int main(){ 
    ABC a; 
    return 0; 
} 

我得到以下輸出:

默認的構造被稱爲!
帶參數2 3調用的參數化構造函數!
-858993460 -858993460

不應成員變量與值2和3被初始化?

+0

'ABC(2,3);'創建一個本地速度爲'ABC'的實例。 –

+0

[爲什麼我應該更喜歡使用成員初始化列表?](http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – LogicStuff

+0

@πάνταῥεῖ那麼我應該如何在同一個對象上進行更改? – Ashish

回答

3

ABC(2, 3);不會調用構造函數初始化該成員,它只是創造將被立即銷燬臨時變量。

如果你的意思是delegating constructor你應該:

ABC() : ABC(2, 3) { 
    cout << "Default constructor called!" << endl; 
    cout << x << " " << y << endl; 
} 

注意,這是一個C++ 11功能。如果你不能使用C++ 11,你可以添加一個成員函數。

class ABC { 
private: 
    int x, y; 
    init(int i, int j) { 
     x = i; 
     y = j; 
    } 
public: 
    ABC(){ 
     cout << "Default constructor called!" << endl; 
     init(2, 3); 
     cout << x << " " << y << endl; 
    } 
    ABC(int i, int j){ 
     cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl; 
     init(i, j); 
     cout << x << " " << y << endl; 
    } 
}; 
1

您在ABC()正文中創建了一個臨時變量。你可以使用這個語法來解決這個問題:

class ABC 
{ 
private: 
    int x, y; 
public: 
    ABC() : ABC(2,3) 
    { 
     std::cout << "Default constructor called!" << std::endl; 
    } 
    ABC(int i, int j) 
    { 
     std::cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << std::endl; 
     x = i; 
     y = j; 
     std::cout << x << " " << y << std::endl; 
    } 
}; 
+0

我無法在IDE上編譯此代碼塊我正在使用(Visual Studio 2010 Professional)。 >錯誤錯誤C2614:'ABC':非法成員初始化:'ABC'不是基礎或成員 – Ashish

+1

@Ashish這僅適用於當前的C++ 11標準。 VS2010太舊了。 –

相關問題