关于在 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;
}
编译此代码时,编译器生成错误消息:“错误 C2662: 'Student::getNo' : 无法将 'this' 指针从 'const Student' 转换为 'Student &'< /code>"
但如果我设置了 no
变量 public
并更改了错误行,例如: os << s.no;
然后事情就完美了。 我不明白为什么会发生这种情况。 有人可以给我一个解释吗? 谢谢。
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 << 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
s
在该方法中是const
,但Student::getNo()
不是const
方法。它必须是const
。这是通过如下更改代码来完成的:
此位置的
const
意味着此整个方法在执行时不会更改this
的内容被称为。Because
s
isconst
in that method, butStudent::getNo()
isn't aconst
method. It needs to beconst
.This is done by changing your code as follows:
The
const
in this position means that this entire method does not change the contents ofthis
when it is called.