| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1281 人关注过本帖
标题:关于友元函数无法访问类中私有变量
只看楼主 加入收藏
ryzenshaw
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2018-3-5
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:2 
关于友元函数无法访问类中私有变量
#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_

搜索更多相关主题的帖子: complex real operator const std 
2018-03-05 21:22
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9031
专家分:54061
注 册:2011-1-18
收藏
得分:20 
根据编译错误提示,增加了include iostream, 改两处return为return is后编译成功

你用的是什么编译器?如果是tc或vc6的话,当我没问过
2018-03-05 21:40
ryzenshaw
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2018-3-5
收藏
得分:0 
回复 2楼 rjsp
我用的vs2017,做一道题,没考虑到头文件,多谢
2018-03-05 21:43
快速回复:关于友元函数无法访问类中私有变量
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.026759 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved