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;
那麼事情就完美了。 我不明白爲什麼會發生這種情況。 任何人都可以給我一個解釋嗎? 謝謝。
這意味着我必須:const int getNo()??但它也沒有工作。 – ipkiss
@ipkiss:我已經更新了Andrew的回答,以說明如何做到這一點。 –