2011-07-05 2 views
0

C++에서 커스텀 I/O 연산자에 관한 질문?

다음 코드 조각이 있습니다.

 class Student { 
public: 
    Student(){} 
    void display() const{} 
    friend istream& operator>>(istream& is, Student& s){return is;} 
    friend ostream& operator<<(ostream& os, const Student& s){return os; } 
}; 
int main() 
{ 
    Student st; 
    cin >> st; 
    cout << st; 

    getch(); 
    return 0; 
} 

friend 키워드를 생략 할 때 연산자가 Student 클래스의 멤버 함수가되도록 시도한 다음 컴파일러에서 "binary 'operator >>' has too many parameters"을 생성합니다. 모든 멤버 함수가 항상 "this"라는 암시 적 매개 변수를 받기 때문에 (즉 모든 멤버 함수가 private 변수에 액세스 할 수 있기 때문에) 일어난 일부 문서를 읽었습니다. 그 설명을 바탕으로, 나는 다음과 같이 노력했다 :

class Student { 
public: 
    Student(){} 
    void display() const{} 
    istream& operator>>(istream& is){return is;} 
    ostream& operator<<(ostream& os){return os; } 
}; 
int main() 
{ 
    Student st; 
    cin >> st; 
    cout << st; 

    getch(); 
    return 0; 
} 

그리고 "error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'Student' (or there is no acceptable conversion)"

누구나 내게 명확한 설명을 주시겠습니까?

답변

0

이 기능은 친구 기능이라고 말할 수 없으며, 그 기능을 인라인으로 포함 할 수 없습니다. friend 키워드는 함수가 클래스에 정의되어 있지 않지만 클래스의 모든 개인 및 보호 된 변수에 액세스 할 수 있음을 의미합니다. 또 다른 예를 들어 http://www.java2s.com/Code/Cpp/Overload/Overloadstreamoperator.htm에서

class Student { 
    public: 
    Student(){} 
    void display() const{} 
    friend istream& operator>>(istream& is, Student& s); 
    friend ostream& operator<<(ostream& os, const Student& s); 
}; 

istream& operator >>(istream& is, Student& s) { return is; } 
ostream& operator <<(ostream& os, const Student& s) { return os; } 

봐 : 당신의 코드를 변경합니다.

< < 및 >>와 함께 왼쪽 피연산자는 항상 파일 스트림이므로 실제 클래스에서 오버로드 할 수 없습니다 (기술적으로 파일 스트림 클래스에 있어야 함).

0

나는 연산자가 정의 된 곳을 잊어 버렸지 만, 전역 연산자 >> 나 스트림에 속한 연산자가 될 것입니다.

학생에서 정의하는 것이 잘못된 장소입니다.