2012-03-21 76 views
0

我正在進行任務,並在特定區域遇到了牆壁。我無法弄清楚我應該如何將非成員函數從頭文件實現到.cpp文件中。這裏是頭:實施非會員功能

class complx 
{ 
    double real, imag; 
public: 
    complx(double real = 0., double imag = 0.); // constructor 
    complx operator+(complx);  // operator+() 

    complx operator+(double);  // operator+()with double 
    complx operator- (complx);  // operator-() 
    complx operator* (complx);  // operator*() 

    bool operator== (complx); // operator==() 


    //Sets private data members. 
    void Set(double new_real, double new_imaginary) { 
     real = new_real; 
     imag = new_imaginary; 
    } 

    //Returns the real part of the complex number. 
    double Real() { 
     return real; 
    } 

    //Returns the imaginary part of the complex number. 
    double Imaginary() { 
     return imag; 
    } 
}; 

ostream &operator << (ostream &out_file, complx number); 

extern istream &operator >> (istream &in_file, complx &number); 

extern ifstream &operator >> (ifstream &in_file, complx &number); 

complx &operator + (double, complx); 
complx &operator - (double, complx); 
complx &operator * (double, complx); 
} 

我有大部分的成員函數想通了,但它是三個在那些給我適合頭的底部。任何幫助將不勝感激。謝謝!

p.s.抱歉格式化,它沒有很好地複製。

+0

首先,簽名是錯誤的。沒有非臨時對象返回引用。按價值返回。 – 2012-03-21 18:27:45

+3

查找並替換4個空格的標籤,然後粘貼,選擇並按下「格式代碼」按鈕(「{}'圖標)。 – 2012-03-21 18:28:14

+0

我真的不相信你可以在頭部的底部實現六個操作符中的任何一個。是的,您可以爲班級重載一名操作員。不,我不相信你可以在沒有班級的情況下超負荷操作員*如果這甚至是你實際想要做的事情...... – paulsm4 2012-03-21 18:29:26

回答

0

在你.ccp文件雲:

ostream &operator << (ostream &out_file, complx number) 
{ 
    out_file << number.Real() << "," << number.Imaginary(); 
    return out_file; 
} 

同樣,對於其他人。

關鍵是要分解複數爲它的元素(實部和虛部)和那些執行所需的操作(併爲+-*返回值創建一個新的複雜的對象)。

+0

非常感謝你的幫助,我想我現在通過流&運算符部分得到它。我仍然不確定你的意思是爲操作符的返回值創建一個新的複雜對象? – 2012-03-21 18:59:22

+0

'operator +'的返回類型是'complx',所以您將不得不創建從操作符返回的複雜對象。該返回的對象將具有double和輸入參數的實數值以及與輸入參數相同的虛數值的和。 (這是假設double必須添加到實部,而不是虛部或兩者)。對於其他運營商也是如此。 – Attila 2012-03-21 19:10:43

+0

好吧,我想通了。再次感謝你的幫助。 – 2012-03-21 19:30:13