2017-05-06 1 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

연산자 '<<'및 '>>'연산자는 비 멤버 함수이어야한다. – 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'friend'는 정의가 아니라 구현에 필요합니다. – Mureinik