开发者

Question about calling method inside custom IO operator in C++?

I have the following code:

#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 << 开发者_JAVA百科s.getNo(); // Error here
     return os;
}
int main()
{
    Student st;
    cin >> st;
    cout << st;
    getch();
    return 0;
}

When compiling this code, the compiler produced the error message: "error C2662: 'Student::getNo' : cannot convert 'this' pointer from 'const Student' to 'Student &'"

But if I made the no variable public and change the error line like: os << s.no; then things worked perfectly. I do not understand why this happened. Can anyone give me an explanation, please? Thanks.


Because s is const in that method, but Student::getNo() isn't a const method. It needs to be const.

This is done by changing your code as follows:

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

The const in this position means that this entire method does not change the contents of this when it is called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜