[英]How to rectify private error while using Friend Function in C++?
Getting this error while using friend function in C++ : error: 'int complex::a' is private within this context.在 C++ 中使用友元函数时出现此错误:错误:'int complex::a' 在此上下文中是私有的。 How will I rectify this error?
我将如何纠正此错误? I have created one complex class and while learning a friend function, i get to know that friend function can access private member functions too.
我创建了一个复杂的类,在学习友元函数时,我了解到友元函数也可以访问私有成员函数。 But in this code, this error pops out.
但是在这段代码中,会弹出这个错误。 Thanks in advance.
提前致谢。
#include <iostream>
using namespace std;
class complex{
private:
int a, b;
public:
void setNumber(int x,int y){a=x;b=y;}
void getNumber(){cout << "\n a="<< a << "b=" << b; }
friend ostream& operator <<(ostream&, complex);
friend istream& operator >>(istream&, complex&);
};
ostream& operator <<(ostream &dout, complex c){
cout << "a=" << c.a;
cout << "b=" << c.b;
return (dout);
}
istream& operator <<(istream &din, complex &c){
cin>>c.a>>c.b;
return (din);
}
int main(){
complex c1;
cin >> c1;
cout << c1;
return 0;
}
change this改变这个
ostream& operator <<(ostream &dout, complex c)
{
cout << "a=" << c.a;
cout << "b=" << c.b;
return (dout);
}
istream& operator <<(istream &din, complex &c)
{
cin>>c.a>>c.b;
return (din);
}
to到
ostream& operator <<(ostream &dout, const complex& c)
{
dout << "a=" << c.a;
dout << "b=" << c.b;
return (dout);
}
istream& operator >>(istream &din, complex &c)
{
din>>c.a>>c.b;
return (din);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.