2012-01-06 59 views
3

類成員的初始化是否有可能initializate這樣一類?C++採用巢式構造

Quaternion::Quaternion(){ //default without arguments 
    Quaternion(0.,V3(0.,0.,0.)); 
} 


Quaternion::Quaternion(double s, V3 v){ //with scalar and vector as a argument 
    coords[0] = s; 
    coords[1] = v[0]; 
    coords[2] = v[1]; 
    coords[3] = v[2]; 
} 

,因爲這是輸出:

QUATERNION TEST 
(2.122e-313:-3.22469e-232:2.122e-313:-1.998) //instanciated with Quaternion q; 
(4:1:2:3) // instanciated with the Quaternion q(4,1,2,3); 
(4:-1:-2:-3) // conjugated of the one above 

和第一個不initializated爲0,因爲它應該是...爲什麼?

回答

13

不是在C++ 03,但近期C++的版本允許委託構造函數:

Quaternion() : Quaternion(0.0, V3(0.0,0.0,0.0)) { } 

在委託構造函數,初始化列表中必須有精確的一個元素,這是另一個構造函數(和顯然不能有任何循環引用)。

Pre-C++ 11如果你真的想實際上初始化你的類成員直接在構造函數中,你不真正複製/粘貼。但是,也許你想使用默認參數?有些人反對那些....

explicit Quaternion(double s = 0.0, V3 v = V3(0.0,0.0,0.0)) { /* ... */ } 
4
Quaternion(0.,V3(0.,0.,0.)); 

這不叫其他的構造函數;相反,它會創建一個本地臨時對象,在構造函數返回時將被放棄。

在C++ 03,你唯一的選擇是在初始化構造雙方所有成員,或將初始化到一個單獨的功能,這兩個構造調用。

在C++ 11,你可以委託給不同的構造函數,使用語法稍有不同:

Quaternion::Quaternion() : 
    Quaternion(0.,V3(0.,0.,0.)) 
{} 
1

您在Quaternion::Quaternion()創建一個臨時的實例。如果你不想讓每個構造函數,定義一個初始化成員函數,例如init()或等到在你的編譯器實現在C++ 11委派構造函數。

2

這是一個名爲的功能,委託構造函數,實際上是在C++ 11中引入的,它之前沒有提供。需要注意的是實際的語法如下不同:

Quaternion::Quaternion() //default without arguments 
    : Quaternion(0.,V3(0.,0.,0.)) // delegating constructor 
{ 
} 


Quaternion::Quaternion(double s, V3 v) //with scalar and vector as a argument 
    : coords{ s, v[0], v[1], v[2] } // better version if you're using C++11 anyways 
{ 
} 

你的代碼所做的是,它創造了被立刻破壞臨時Quaternion對象。

1

默認構造函數只是調用兩個參數的構造。然後將生成的Object放入堆棧,並在離開構造函數時將其解構。

所以四元數0 initilisation時不帶參數的四元數的施工時間只有靜物,但它不是四元數,這是默認的構造函數構造。

你可以做的是,要asssign標準值參數:

#include <cstdio> 

class TestCl { 
public: 
    TestCl(int i = 0) { 
    printf("%d\n", i); 
    }; 
}; 

int main(int argc, char** argv) { 
    TestCl f(1); 
    TestCl s; 
    return 0; 
}