2011-07-06 5 views
0

나는 다음과 같은 코드가 있습니다C++에서 사용자 지정 IO 연산자의 메서드 호출에 대한 질문?

#include "iostream" 
#include "conio.h" 
using namespace std; 
class Student { 
private: 
    int no; 
public: 
    Student(){} 
    int getNo() { 
     return this->no; 
    } 
    friend istream& operator>>(istream& is, Student& s); 
    friend ostream& operator<<(ostream& os, const Student& s); 
}; 
ostream& operator<<(ostream& os, const Student& s){ 
    os << s.getNo(); // Error here 
    return os; 
} 
int main() 
{ 
    Student st; 
    cin >> st; 
    cout << st; 
    getch(); 
    return 0; 
} 
이 코드를 컴파일 할 때 컴파일러 오류 메시지가 발생

"error C2662: 'Student::getNo' : cannot convert 'this' pointer from 'const Student' to 'Student &'"

을하지만이 no 변수 public을 만들어 같은 오류 라인을 변경하는 경우 : os << s.no;를 그 때 일은 완벽하게 작동했습니다. 나는 왜 이것이 일어 났는지 이해하지 못합니다. 누구든지 설명해 주시겠습니까? 감사합니다. .

답변

2

이이 방법에서는 const이므로 Student::getNo()const 메서드가 아니기 때문에. const이어야합니다.

이 다음과 같이 코드를 변경하여 수행됩니다

int getNo() const { 
    return this->no; 
} 

이 위치에 const 즉,이 호출 될 때 this의 내용을 변경하지 않는이 전체 방법.

+0

즉, 다음과 같이해야합니다. const int getNo() ?? 그러나 그것은 또한 작동하지 않았다. – ipkiss

+0

@ipkiss : 어떻게해야하는지 앤드류의 대답을 업데이트했습니다. –

관련 문제