2016-04-28 96 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 <'两次。一次作为成员函数,一次作为非成员函数。也许我不清楚,但我只是向你展示了两种可能性。你需要选择一个,而不是两个都使用。否则你有歧义。 –