关于友元函数无法访问类中私有变量
#ifndef COMPLEX0_H_#define COMPLEX0_H_
class complex {
private:
double real;
double imaginary;
public:
complex();
complex(double r, double i);
~complex();
complex operator+(const complex &c)const;
complex operator-(const complex &c)const;
complex operator*(const complex &c)const;
friend complex operator*(double d, const complex &c);
friend std::ostream& operator<<(std::ostream &os, const complex &c);
friend std::istream& operator>>(std::istream &is, complex &c);
};
complex::complex()
{
real = imaginary = 0;
}
complex::complex(double r, double i) {
real = r;
imaginary = i;
}
complex::~complex() {
}
complex complex::operator+(const complex &c)const {
return complex(real + c.real, imaginary + c.imaginary);
}
complex complex::operator-(const complex &c)const {
return complex(real - c.real, imaginary - c.imaginary);
}
complex complex::operator*(const complex &c)const {
return complex(real*c.real - imaginary * c.imaginary, real*c.imaginary + c.real + imaginary);
}
complex operator*(double d, const complex &c) {
return complex(d*c.real, d*c.imaginary);
}
std::ostream& operator<<(std::ostream &os, const complex &c) {
os << "(" << c.real << "," << c.imaginary << "i)" << "\n";//这里的real和imaginary变量无法访问
return os;
}
std::istream& operator>>(std::istream &is, complex &c) {
std::cout << "real:";
is >> c.real;//这里也是
if (c.real == 'q')
return;
std::cout << std::endl << "imaginary:";
is >> c.imaginary;
if (c.imaginary == 'q')
return;
return is;
}
#endif // !COMPLEX0_H_