2012-02-01 4 views
4

삽입 연산자를 오버로드하는 클래스를 작성하려고하지만 헤더 파일에 오류가 발생합니다. 여기 오버로드 C++ 삽입 연산자 (<<)

Overloaded 'operator<<' must be a binary operator (has 3 parameters) 

내 코드입니다 :

.H 파일

ostream & operator<<(ostream & os, Domino dom); 

.cpp 파일 I 텍스트 책을 다음있어이은으로 무엇을 사용

ostream & operator<< (ostream & os, Domino dom) { 
    return os << dom.toString(); 
} 

예를 들어,하지만 나를 위해 일하지 .. 어떤 제안?

+4

"비트 왼쪽 시프트 연산자"라고하지 않았습니까? – SigTerm

+0

큰 코드가 아닌 경우 전체 코드로 질문을 업데이트 할 수 있습니까? –

+0

'operator <<'는 클래스 멤버가 될 수 없습니다. 친구 여야합니다! –

답변

14

아마도 operator<<을 클래스 선언 안에 넣었을 것입니다. 즉, 추가 숨겨진 매개 변수 (매개 변수)가 필요합니다. 클래스 선언 외부에 넣어야합니다.

10

삽입 연산자 (< <)는 멤버 함수 또는 friend 함수로 사용할 수 있습니다. 사용자가 멤버 함수 연산자를 사용하는 경우, 일반적으로

dom << cout; 

좌측 :

ostream& operator<<(ostream& os); 

멤버 함수로서 사용

연산자 < <이 함수로 호출되어야 작업자의 손 쪽이 객체 여야합니다. 그런 다음이 객체는 암시 적으로 멤버 함수에 인수로 전달됩니다. 그러나 호출은 사용자를 혼란스럽게하고 멋지지 않습니다. 오브젝트 dom 명시 적으로 참조로 전달되고이 경우

cout << dom; 

:로

연산자 < < 친구 기능

friend ostream& operator<<(ostream& os, const Domino& obj); 

이 기능으로 사용이 호출되어야한다. 이 호출은보다 전통적이며 사용자는 코드의 의미를 쉽게 이해할 수 있습니다.

0
/*insertion and extraction overloading*/ 
#include<iostream> 
using namespace std; 
class complex 
{ 
    int real,imag; 

public: 
    complex() 
    { 
     real=0;imag=0; 
    } 
    complex(int real,int imag) 
    { 
     this->real=real; 
     this->imag=imag; 
    } 
    void setreal(int real) 
    { 
     this->real=real; 
    } 
    int getreal() 
    { 
     return real; 
    } 
    void setimag(int imag) 
    { 
     this->imag=imag; 
    } 
    int getimag() 
    { 
     return imag; 
    } 
    void display() 
    { 
     cout<<real<<"+"<<imag<<"i"<<endl; 
    } 

};//end of complex class 

istream & operator >>(istream & in,complex &c) 
    { 
     int temp; 
     in>>temp; 
     c.setreal(temp); 
     in>>temp; 
     c.setimag(temp); 
     return in; 
    } 
ostream &operator <<(ostream &out,complex &c) 
{ 
    out<<c.getreal()<<c.getimag()<<endl; 
    return out; 
} 

int main() 
{ 
    complex c1; 
    cin>>c1; 
// c1.display(); 

    cout<<c1; 
    //c1.display(); 
    return 0; 
} 
+0

삽입 친구 함수를 사용하지 않고 추출 과부하 –