注册 登录
编程论坛 C++教室

关于友元函数无法访问类中私有变量

ryzenshaw 发布于 2018-03-05 21:22, 1433 次点击
#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_

2 回复
#2
rjsp2018-03-05 21:40
根据编译错误提示,增加了include iostream, 改两处return为return is后编译成功

你用的是什么编译器?如果是tc或vc6的话,当我没问过
#3
ryzenshaw2018-03-05 21:43
回复 2楼 rjsp
我用的vs2017,做一道题,没考虑到头文件,多谢
1