2013-09-24 61 views
1

有簡單的代碼,我在C++教程中找到。但我不明白這一行:構造函數在這一行中做了什麼?

c1 = Complex(10.0); 

在評論中寫道,可以使用構造函數從一種類型轉換到另一種。有人可以解釋這一刻。感謝您的任何幫助。

#include <iostream> 
using namespace std; 

class Complex 
{ 
    public: 
    Complex() : dReal(0.0), dImag(0.0) 
    { cout << "invoke default constructor" << endl;} 
    /*explicit*/ Complex(double _dReal) 
     : dReal(_dReal), dImag(0.0) 
    { cout << "invoke real constructor " << dReal <<endl;} 
    Complex(double _dReal, double _dImag) 
     : dReal(_dReal), dImag(_dImag) 
    { 
     cout << "invoke complex constructor " << dReal 
      << ", " << dImag << endl; 
    } 

    double dReal; 
    double dImag; 
}; 

int main(int argcs, char* pArgs[]) 
{ 
    Complex c1, c2(1.0), c3(1.0, 1.0); 

    // constructor can be used to convert from one type 
    // to another 
    c1 = Complex(10.0); 

    // the following conversions work even if explicit 
    // is uncommented 
    c1 = (Complex)20.0; 
    c1 = static_cast<Complex>(30.0); 

    // the following implicit conversions work if the 
    // explicit is commented out 
    c1 = 40.0; 
    c1 = 50; 

    system("PAUSE"); 
    return 0; 
} 
+0

可能將雙數值10.0d轉換爲複數,實數部分等於10.0d,虛數部分等於零。 – Rekin

回答

3

這在這裏:

Complex(double _dReal) 
     : dReal(_dReal), dImag(0.0) 
    { cout << "invoke real constructor " << dReal <<endl;} 

是一個構造函數,將採取double,它會從它創建Complex對象。你可以看到,它將設置實部(dReal)傳遞給構造函數(_dReal)的值,它會建立虛部到0

這條線:

c1 = Complex(10.0); 

會調用該構造函數,它將轉換成將實數(10.0)轉換爲Complex對象。

編輯:請注意,這不是真正的轉換 - 這是明確傳遞一倍,它創建Complex對象的 - 你必須通過dasblinkedlight提供的答案轉換的例子。

1

c1 = Complex(10.0);創建一個Complex對象並將其複製到c1

2

c1 = Complex(10.0); 

電話其實這樣的:

Complex(double _dReal) 
    : dReal(_dReal), dImag(0.0) 
{ 
    cout << "invoke real constructor " << dReal <<endl; 
} 

此構造只是初始化成員dReal用在參數傳遞的價值並初始化dImag0.0

當他們說你可以將一種類型轉換爲另一種類型時,我想他們想說你可以將double「轉換」爲Complex

1

對於任何給定類型T和對象x表達T(x)(或對象x1,x2...)創建臨時使用給定參數構造T類型。

3

這不是一個轉換,因爲構造明確一個Complex對象:

c1 = Complex(10.0); 

然而,這是一個換算:

c1 = (Complex)20.0; 

等等是這樣的:

c1 = static_cast<Complex>(30.0); 

即使構造函數是顯式的,上面的兩個轉換都可以工作,因爲它們會調用轉換呃...明確地說。

另外兩個不具有顯式的構造工作:

c1 = 40.0; 
c1 = 50; 

在這裏,轉換是隱式的,即,操作由分配的左手邊的類型隱含,並且存在一個構造函數在右邊表達一個表達式。編譯器不能在這種情況下應用聲明爲explicit的構造函數,因此如果您在上面的聲明中取消註釋explicit,則此代碼段不會編譯。

1

c1 = Complex(10.0);調用你的隱式構造/*explicit*/ Complex(double _dReal)

的評論說,你可以轉換到double類型Complex

在您明確被刪除的情況下,您可以聲明Complex c1 = 10.0 ;,這將隱含地爲您調用Complex(double _dReal)。然而,如果顯式未被評論,它將禁止「自動」轉換,並且您將被迫聲明Complex(10.0)以便將double「轉換」爲Complex

相關問題