2015-12-31 80 views
-2

目前,即時通訊工作在一個CVector類,一切工作正常,直到我想在其他類如CVector v;中使用矢量和稍後使用v類有不止一個構造函數

好,問題就出在那裏 - 我會用

struct Vector3_t { 
    float x, y , z; 

}; 

,但我想使用運營商的載體,所以我做了一個類:

class CVector 
{ 
public: 

    //missing usage: CVector vec; // for later usage in example. 
    CVector() // usage: CVector v(); 
    { 
     this->x = 0, this->y = 0, this->z = 0; 
    } 

    CVector(const float x = 0, const float y = 0) { // usage: CVector v(1,2); // but z is always 0 
     this->x = x, this->y = y,this->z = 0; 
    } 

    CVector(const float x = 0, const float y = 0, const float z = 0) { // usage: CVector v(1,2,3); 
     this->x = x, this->y = y, this->z = z; 
    } 

    CVector & CVector::operator += (const CVector & v) { 
     this->x += v.x; this->y += v.y; this->z += v.z; return *this; 
    } 
    const CVector CVector::operator + (const CVector& v) const { 
     CVector r(*this); return r += v; 
    } 

    float x, y, z; 
    ~CVector() {}; 
protected: 

private: 
}; 

在行動:

int main() { 

    CVector vec; 
    return 0; 
} 

輸出錯誤: 嚴重級代碼說明項目文件行抑制狀態 錯誤(活動)類「CVector」具有多個默認構造函數mebad c:\ Users \ lifesucks \ Documents \ Visual Studio 2015 \ Projects \ mebad \ mebad \ main.cpp 43

*嚴重級代碼說明項目文件行抑制狀態 錯誤C2668'CVector :: CVector':模糊調用重載函數mebad c:\ users \ lifesucks \ documents \ visual studio 2015 \ projects \ mebad \ mebad \ main.cpp 43
*

基本上我只是不知道如何爲這種類型的用途聲明類時,有多個構造函數,我不想用更多的樂趣像CVector :: constr1那樣使用3個浮動或類似的東西,必須有辦法這樣做,我可以得到一些幫助嗎?謝謝!

+0

_「但我想使用運營商的載體,所以我做了一類」 _'struct's可以有操作符重載過。 – emlai

+1

@格雷特不應該在那裏,我只是試圖顯示用戶使用不同的方式,但沒有發現它,給我秒我會編輯它不會錯誤,如果我想用這種方式與類,可以我得到一個幫助?這非常有趣,我不會另外提問。 –

+1

當發佈有關錯誤的代碼問題時,請在問題主體中包含* all *輸出,完成並未經編輯。 –

回答

3

問題是你使用兩個構造函數的參數的默認值,這意味着你有三個構造函數可以在沒有參數的情況下被調用,那麼編譯器應該調用哪個?

只需刪除默認參數值,它應該工作。

+3

或者更好的辦法是,除了三個參數的構造函數外,全部刪除。 – emlai

+0

你是什麼意思的參數值?你想我刪除構造函數或'this-> x = 0'等? –

+0

參數VALUES是你的函數定義中的「= 0」等。 – Grantly

0

你的類應該是

class CVector 
{ 
public: 
    CVector() : x(0), y(0), z(0) {} 
    CVector(float x) : x(x), y(0), z(0) {} 
    CVector(float x, float y) : x(x), y(y), z(0) {} 
    CVector(float x, float y, float z) : x(x), y(y), z(z) {} 

    //... 

    float x, y, z; 
}; 

class CVector 
{ 
public: 
    CVector(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(z) {} 

    //... 

    float x, y, z; 
}; 
0

約阿希姆Pileborg完美地回答了這一點,值得點。

以下是代碼更改你chould做:

CVector() // usage: CVector v(); 
{ 
    this->x = 0, this->y = 0, this->z = 0; 
} 

CVector(const float x, const float y) { // usage: CVector v(1,2); // but z is always 0 
    this->x = x, this->y = y,this->z = 0; 
} 

CVector(const float x, const float y, const float z) { // usage: CVector v(1,2,3); 
    this->x = x, this->y = y, this->z = z; 
} 
相關問題