[英]Can't access private members of a class despite friend class
I am doing a homework assignment on overloading operators.我正在做关于重载运算符的家庭作业。 This is my code:
这是我的代码:
#include<iostream>
#include<cmath>
using namespace std;
class ComplexNumber{
double real;
double imaginary;
public:
friend class Equation;
};
class Equation{
ComplexNumber *broevi;
char *znaci;
int n;
public:
Equation(){
broevi=new ComplexNumber[0];
znaci=new char[0];
n=0;
}
friend istream &operator >>(istream &in, Equation &e){
int k=1;
while(k){
char *tmp; ComplexNumber *b;
tmp=new char[e.n+1];
for(int i=0; i<e.n; i++)
tmp[i]=e.znaci[i];
b=new ComplexNumber[e.n+1];
for(int i=0; i<e.n; i++)
b[i]=e.broevi[i];
in>>e.broevi[e.n].real>>e.broevi[e.n].imaginary;
in>>tmp[e.n];
if(tmp[e.n]=='=')
break;
delete []e.znaci;
e.znaci=tmp;
delete[]e.broevi;
e.broevi=b;
++e.n;
}
return in;
}
friend class ComplexNumber;
};
This is only a part of my code.这只是我的代码的一部分。
While compiling I get these two following errors:编译时出现以下两个错误:
error: 'double ComplexNumber::imaginary' is private
错误:'double ComplexNumber::imaginary' 是私有的
error: 'double ComplexNumber::real' is private
错误:'double ComplexNumber::real' 是私有的
On this line:在这条线上:
in>>e.broevi[e.n].real>>e.broevi[e.n].imaginary;
Can you please point out where my mistake is?你能指出我的错误在哪里吗?
Your operator>>
is a friend of Equation
, so it can access private fields of Equation
.您的
operator>>
是Equation
的朋友,因此它可以访问Equation
的私有字段。 But, it is not a member of Equation
, and it is not a friend
of ComplexNumber
, so it can't access private fields of ComplexNumber
.但是,它不是
Equation
的成员,也不是ComplexNumber
的friend
,因此它不能访问ComplexNumber
的私有字段。
The simplest solution is to add a friend operator>>
to ComplexNumber
, and then use that in Equation'
s operator>>
:最简单的解决方案是将友元
operator>>
添加到ComplexNumber
,然后在Equation'
的operator>>
中使用它:
class ComplexNumber {
double real;
double imaginary;
public:
friend istream& operator >>(istream &in, ComplexNumber &cn) {
in >> cn.real >> cn.imaginary;
return in;
}
};
class Equation {
...
public:
...
friend istream& operator >>(istream &in, Equation &e) {
...
//in >> e.broevi[e.n].real >> e.broevi[e.n].imaginary;
in >> e.broevi[e.n];
...
}
};
However, if that is not allowed for your assignment, then you can instead move your stream logic to a member method of Equation
for its operator>>
to call, and then that method will have access to the private fields of ComplexNumber
:但是,如果您的分配不允许这样做,那么您可以将 stream 逻辑移动到
Equation
的成员方法以供其operator>>
调用,然后该方法将有权访问ComplexNumber
的私有字段:
class ComplexNumber {
double real;
double imaginary;
public:
friend class Equation;
};
class Equation {
...
void read(istream &in) {
// your logic here...
}
public:
...
friend istream& operator >>(istream &in, Equation &e){
e.read(in);
return in;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.