У меня есть следующий код:
#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;
тогда все заработало отлично.Я не понимаю, почему это произошло.Кто-нибудь может дать мне объяснение, пожалуйста?Благодаря.