2017-05-06 31 views
0

首先是我得到的錯誤:不能超載<<這一切操作

error: overloaded 'operator<<' must be a binary operator (has 3 parameters) std::ostream& operator<< (std::ostream& os, const Dcomplex& c);

,我只是不明白爲什麼。我讀了其他幾個問題,他們都說只是添加const,但它不適合我。

所以這是我的頭文件:

#ifndef AUFGABE5_DCOMPLEX_H 
#define AUFGABE5_DCOMPLEX_H 

class Dcomplex { 
private: 
    double re, im; 

public: 
    Dcomplex(double r = 0, double i = 0); 
    Dcomplex(const Dcomplex& kopie); 
    ~Dcomplex(); 

    double abswert() const; 
    double winkel() const; 
    Dcomplex konjugiert() const; 
    Dcomplex kehrwert() const; 
    Dcomplex operator+(const Dcomplex& x)const; 
    Dcomplex operator-(); 
    Dcomplex operator*(const Dcomplex& x)const; 
    Dcomplex operator-(const Dcomplex& x)const; 
    Dcomplex operator/(const Dcomplex& x)const; 
    Dcomplex& operator++(); 
    Dcomplex& operator--(); 
    const Dcomplex operator++(int); 
    const Dcomplex operator--(int); 

    std::ostream& operator<< (std::ostream& os, const Dcomplex& c); 
    std::istream& operator>> (std::istream& is, const Dcomplex& c); 

    bool operator>(const Dcomplex &x)const; 

    void print(); 
}; 

#endif //AUFGABE5_DCOMPLEX_H 

我感謝爲什麼它不工作的想法。

編輯:

std::istream& Dcomplex::operator>>(std::istream &is, const Dcomplex& c) { 

    double re,im; 

    std::cout << "Der Realteil betraegt?"; is >> re; 
    std::cout << "Der Imaginaerteil betraegt?"; is >> im; 

    Dcomplex(re,im); 

    return is; 
} 
+1

'的operator <<'和'操作者>>'必須爲非成員函數。 – songyuanyao

回答

0

如果一個類中寫一個正操作符重載函數,該函數的第一個參數始終是類本身。你不能指定另一個。沒有接受3個參數的操作員(?:除外,但不能覆蓋此參數)。如果你想寫第一個參數不是類本身,你可以嘗試使用朋友函數。

class Dcomplex { 
    // some stuff 
    friend std::ostream& operator<<(std::ostream& os, const Dcomplex& c); 
    friend std::istream& operator>>(std::istream& is, Dcomplex& c); 
} 

std::ostream& operator>>(std::ostream& os, const Dcomplex& c){ 
    // Define the output function 
} 
std::istream& operator>>(std::istream& is, Dcomplex& c){ 
    // Define the input function 
} 
+0

啊,現在我知道了,它的工作原理。但我的教授從來沒有說過,我需要在那裏使用一個朋友功能,但它的工作原理和非常感謝! –

0

的第一個參數的操作符是「本」,所以如果你聲明兩個參數,操作者將實際拿到三 - 「這個」,你聲明的兩個參數。它好像你的意思是它聲明爲一個friend

friend ostream& operator<<(ostream& os, const Dcomplex& c); 
+0

好吧謝謝你爲.h工作,但現在我得到了同樣的錯誤在我的.cpp,但我不能在那裏使用朋友..對不起,如果這些都是愚蠢的問題,我剛剛開始與CPP。 .cpp在我的主要帖子中。 –

+0

@HenningWilmer'朋友'只是需要定義,而不是實現。 – Mureinik