2016-04-28 65 views
-3

超載爲最大我實現一個新的變量類型(NEWTYPE)與算術運算符(+, - ,*,/)和std ::最大過載。雖然算術運算符工作,但最大函數有一些問題。有人能提供一些我失蹤的指針嗎?操作員在C++

#include <iostream> 
using namespace std; 

class NewType { 
private: 
    float val; 

public: 
    NewType(float v) { val = v; } 
    // Arithmetic operators 
    friend NewType operator+(const NewType &c1, const NewType &c2); 
    friend NewType operator-(const NewType &c1, const NewType &c2); 
    friend NewType operator*(const NewType &c1, const NewType &c2); 
    friend NewType operator/(const NewType &c1, const NewType &c2); 

    float GetVal() { return val; } 

    float max(const NewType &lhs, const NewType &rhs) { return lhs.val > rhs.val ? lhs.val : rhs.val; } 
    }; 

// Arithmetic Operations 
NewType operator+(const NewType &c1, const NewType &c2) { return NewType(c1.val + c2.val); } 
NewType operator-(const NewType &c1, const NewType &c2) { return NewType(c1.val - c2.val); } 
NewType operator*(const NewType &c1, const NewType &c2) { return NewType(c1.val * c2.val); } 
NewType operator/(const NewType &c1, const NewType &c2) { return NewType(c1.val/c2.val); } 


int main() { 

    NewType a = 10.2; 
    NewType b = 8.4; 
    NewType c = a+b; 

    cout << c.GetVal() << std::endl; 

    NewType d = max(a,b); 
    cout << d.GetVal() << endl; 
    return 0; 
} 
+0

'朋友FLOAT MAX(...' –

+3

你打電話'的std :: max',在你的類中定義不是'max'。'的std :: max'使用'運營商<'默認,你還沒有實現 – Cameron

+6

也許它的時間使用該退出:'使用命名空間std;' – drescherjm

回答

2

您已將max作爲非靜態成員函數實施。你會這樣稱呼它:

NewType a(0.0f), b(1.0f), c(2.0f); 
NewType d = a.max(b, c); 

注意a沒有實際需要進行此操作在所有的,除了你聲明max作爲非靜態成員函數的事實。一種解決方案是使其成爲非會員功能。

// outside of the class body 
float max(const NewType &lhs, const NewType &rhs) { 
    return lhs.GetVal() > rhs.GetVal() ? lhs.GetVal() : rhs.GetVal(); 
} 

另一個(更好,IMO)的解決方案是超載operator<爲類,然後你的類將自動std::minstd::max工作,以及算法和容器標準庫中的主機。

// member version, inside the class 
bool operator<(const NewType& rhs) const { 
    return val < rhs.val; 
} 

// non-member version, outside the class 
bool operator<(const NewType& lhs, const NewType& rhs) { 
    return lhs.GetVal() < rhs.GetVal(); 
} 

在附註上,使GetVal爲const。

float GetVal() const { return val; } 
+0

非常感謝您的回答。把最大能根據外界你說工作正常,但其他的想法似乎並不奏效(超載 newType類{ 私人: \t浮子VAL; 公共: \t NEWTYPE(浮動V){VAL = V; } \t bool操作符<(const NewType&rhs)const {return val smjee

+0

@smjee:請注意,'的std :: max'返回傳遞給它(這是應該做的自然的事情)同一類型,因此,如果通過2'NewType'對象將返回一個'NewType'對象。而你的最大功能返回一個浮點數。輸出'operator <<'爲'float'重載,但不是你的類型。所以你可以提供那個重載,或者使用'std :: max(a,b).GetVal()'從'std :: max'的結果中獲得一個浮點數。 –

+0

@smjee:好吧,當我等待時,另一個問題是你重載了'operator <'兩次。一次作爲成員函數,一次作爲非成員函數。也許我不清楚,但我只是向你展示了兩種可能性。你需要選擇一個,而不是兩個都使用。否則你有歧義。 –