2016-04-21 181 views
0

玉傢伙在這裏,我的問題很簡單..我想構建不同勢值類型getter和setter ..基本上函數重載但getter和setter ..我試圖像這樣getter和setter C++

#include <iostream>; 

class Vectors { 
public: 
    Vectors() {}; 
    Vectors(int a, int b) { 
     x = a, y = b; 
    } 
    int getX() { 
     return x; 
    } 
    int getY() { 
     return y; 
    } 
    float getX() { 
     return (float)x; 
    } 
    float getY() { 
     return (float) y; 
    } 
    friend Vectors operator+(const Vectors& v1, const Vectors& v2); 
    friend Vectors operator/(const Vectors& v1, const Vectors& v2); 
protected: 
    int x, y; 
private: 

}; 

Vectors operator+(const Vectors& v1, const Vectors& v2) { 
    Vectors brandNew; 
    brandNew.x = v1.x + v2.x; 
    brandNew.y = v1.y + v2.y; 
    return (brandNew); 
}; 

Vectors operator/(const Vectors& v1, const Vectors& v2) { 
    Vectors brandNew(v1.x/v2.x, v1.y/v2.y); 
    return brandNew; 
} 

int main() { 
    Vectors v1(2, 3); 
    Vectors v2(4, 5); 
    Vectors v3; 
    v3 = v1 + v2; 
    Vectors v4 = v1/v2; 

    std::cout << "VECTOR 4 X : " << v4.getX() << std::endl; 
    std::cout << "VECTOR 4 Y : " << v4.getY() << std::endl; 

    std::cout << "Vector V3 X : " << v3.getX() << std::endl; 
    std::cout << "VECTOR V3 Y : " << v3.getX() << std::endl; 
} 

但顯然它說不能做功能重載和唯一類型不同是返回類型。

+2

所以問題是?爲什麼不在你稱之爲吸氣劑之後進行劇組? –

+0

問題是你怎麼做它告訴我的論據必須是不同的... @BaummitAugen。以上代碼有錯誤... – amanuel2

+0

你不能,根據你的最後一句話是顯而易見的。想一想,如果你編寫'v4.ge​​tX()',編譯器應該怎麼知道你想調用哪個getter?再次,只需要'int' getters並且輸出它們的結果。 –

回答

3

有沒有辦法重載函數不改變,我所知道的參數。您需要調用函數等之後,要麼改變函數名(稱之爲getXFloat()或東西)或者只是演員:

float the_x_value = static_cast<float>(vec.getX()); 

我會去的第二個選項。

+1

在C++中,我推薦使用static_cast 來代替C風格的轉換。 – Rei

+0

你是對的 - 謝謝! – hacoo

0

您擁有的另一個選擇是不返回結果作爲返回值。相反:

... 
void getX(float& result) const { 
    result = static_cast<float>(x); 
} 
void getX(int& result) const { 
    result = x; 
} 
... 

只是添加到選項列表中,並不是說這是最好的解決方案。

4

當然,你沒有使用足夠的模板。模板可以解決C++中的問題。使用它們。愛模板。

struct YeeTemplates { 
    float F; 
    template <typename T> 
    T getF() { return F; } 
} y; 

float f = y.getF<float>(); 
int i = y.getF<int>();