2011-07-06 44 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

因爲在該方法中sconst,但Student::getNo()不是const方法。它需要是const

這是通過改變你的代碼做如下:

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

在這個位置上的const意味着不改變this內容時,它被稱爲這個整個方法。

+0

這意味着我必須:const int getNo()??但它也沒有工作。 – ipkiss

+0

@ipkiss:我已經更新了Andrew的回答,以說明如何做到這一點。 –