2011-07-06 1 views
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;を物事は完璧に働いた。 これがなぜ起こったのか分かりません。 誰でも私に説明を教えてもらえますか?おかげさまで

答えて

2

この方法ではsconstであるため、Student::getNo()constメソッドではないためです。それはconstである必要があります。これは、次のようにコードを変更することによって行われ

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

この位置でconstは、それが呼び出されたときにthisの内容を変更しないこの全体の方法を意味します。

+0

これは私がする必要があることを意味します:const int getNo()??しかし、それはまた動作しませんでした。 – ipkiss

+0

@ipkiss:私はそれを行う方法を示すAndrewの答えを更新しました。 –

関連する問題