0
I次のコードを持っている: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の答えを更新しました。 –