2011-12-01 37 views
2

我想超載(*,+, - ,/,=)opertors在FLOAT類。我寫了這個類:運算符(*,+, - ,/,=)的重載?

class FLOAT{ 
private: 
float x; 
public: 
FLOAT(){ x=0.0; } 
void setFloat(float f)  { x=f; } 
void operator+(FLOAT obj) {x=x+obj.x; }; 
void operator-(FLOAT obj) {x=x-obj.x; }; 
void operator*(FLOAT obj) {x=x*obj.x; }; 
void operator/(FLOAT obj) {x=x/obj.x; }; 
FLOAT& operator=(const FLOAT& obj) {this->x=obj.x; return *this; }; 
}; 

,我使用它,例如:

int main() { 
FLOAT f,f2,f3; 
f.setFloat(4); 
f2.setFloat(5); 

f3=f+f2;// here is the problem! 
    system("pause");//to pause console screen 
return 0; 
} 

f3=f+f2似乎不正確的。我能做什麼?

+2

我強烈推薦複製構造函數和'float'的隱式構造函數。在可能的情況下也通過'const FLOAT&'傳遞對象。 –

+0

@MooingDuck:爲什麼?編譯器生成的copy ctor有什麼問題?事實上,Adban,你可能會失去賦值運算符。編譯器也會提供。 –

+1

@BenjaminLindley:我一直忘記編譯器有時會提供這些。我更願意明確地看到它們,所以我有我的選項列表。分配也一樣。這不是必需的,但也不是空白。 –

回答

8

我想你想你的運營商的實現不會做。例如:

FLOAT f1; f1.setFloat(1.0); 
FLOAT f2; f2.setFloat(2.0); 
FLOAT f3; 
f3 = f1 + f2; 

假設你改變運營商+(),例如,返回一個FLOAT,你仍然會有效果,添加,F1和F3之後將兩者等於3.0;

一個常用的習慣用法是在類中實現像+ =這樣的運算符,而類之外的運算符則像+。例如:

class FLOAT {... 
    FLOAT& operator+=(const FLOAT& f) 
    { 
     x += f.x; 
     return *this; 
    } 
}; 

...

FLOAT operator+(const FLOAT& f1, const FLOAT& f2) 
{ 
    FLOAT result(f1); 
    f1 += f2; 
    return f1; 
} 

這方面的一個附帶的好處是,你還可以輕鬆添加其他運營商如

FLOAT operator+(int x, const FLOAT& f); 
FLOAT operator+(double x, const FLOAT& f); 

做一個徹底的工作像一個類當你想用更復雜的數字或矩陣等更有趣的類型來完成這項工作時,這是一個很好的做法。請確保您添加比較運算符,複製構造函數,析構函數和賦值運算符以獲得完整性。祝你好運!

1

operator+有返回類型void。它應該可能會返回FLOAT

要澄清例如,void operator+(FLOAT obj) {x=x+obj.x; };應該代替像FLOAT operator+(FLOAT obj) { return obj.x + x; }。這是因爲,正如其他人所指出的那樣,隨着void返回類型的函數無法返回任何值。由於operator+通常會返回一個表示加法結果的值,因此應該返回一個包含此結果的FLOAT對象。

+0

雖然準確,但這不是解決問題以及如何解決問題的答案。 –

4

你應該在每一種情況下返回結果。也通過引用傳遞參數,所以它不會被複制並添加一些const限定符。對於+它可能看起來像:

FLOAT operator+(const FLOAT& obj) const 
{ 
    FLOAT res; 
    res.x = x + obj.x; 
    return res; 
} 

你可能不希望返回const,如你想去拿修改的對象。

+2

我的C++很弱,但看起來更像'+ ='而不是'+'。 – CodesInChaos

+0

@CodeInChaos完全正確。它正在做+ =等。 – crashmstr

+0

@CodeInChaos謝謝你。 – Beginner

6

你的運營商的+=-=相當於等 如果你想+,你還需要返回一個值!

FLOAT operator+(FLOAT obj) 
{ 
    FLOAT tmp; 
    tmp.x = x+obj.x; 
    return tmp; 
} 
5

不能void函數的返回值分配到任何東西,因爲它不返回任何東西。將運算符重載聲明爲朋友函數通常要靈活得多。您的類和功能應該更多這樣的:

class FLOAT { 
    friend FLOAT operator+(const FLOAT & a, const FLOAT & b); 

    /* ... rest of class ... */ 
}; 


FLOAT operator+(const FLOAT & a, const FLOAT & b) 
{ 
    FLOAT temp(a); 
    temp.x += b.x; 
    return temp; 
} 
3
void operator+(FLOAT obj) {x=x+obj.x; }; 

這段代碼有什麼問題?

它返回void並且你想把它賦給某個地方。不行。

FLOAT & FLOAT::operator=(const FLOAT &rhs) { 
    ... // todo assignment here 
    return *this; // Return a reference to myself. 
} 

FLOAT & FLOAT::operator+=(const FLOAT &rhs) { 
    ... //todo implement compound + operator 
    return *this; // Return a reference to myself. 
    } 

const FLOAT FLOAT::operator+(const FLOAT &rhs) const { 
    return FLOAT(*this) += other; //that's already done :) 
    }