在我的班级定义中,我具有以下朋友功能:
friend ostream& operator << (ostream& out, const Person& p1);
friend istream& operator >> (ostream& out Person& p1);
在我的授权文件中:
ostream& operator << (ostream& out, const Person& p1)
{
out<< p1.age; //this is a private variable
}
istream& operator << (istream& in, Person& p1)
{
in >> p1.age; //this is a private variable
}
但是,当我对此进行编译时,出现一个错误,提示“ ostream”没有将类型朋友ostream&运算符(ostream&out,const Person&p1)命名为istream。由于这些是朋友功能,因此它们可以访问私有变量,即年龄,这是什么问题?
最佳答案
因此,首先,您的函数应返回某些内容,因此:
ostream& operator << (ostream& out, const Person& p1)
{
return out<< p1.age; //this is a private variable
}
和
istream& operator << (istream& in, Person& p1)
{
return in >> p1.age; //this is a private variable
}
您应该记得添加
include <iostream>
标头。和using namespace std;
最重要的是错别字
friend istream& operator >> (istream& out Person& p1);
关于c++ - operator <<和operator >>重载函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19580970/