频道栏目
首页 > 资讯 > 其他 > 正文

友元函数的使用设置详情

17-11-14        来源:[db:作者]  
收藏   我要投稿

对于一个类的私有成员,只有类的成员函数才能直接访问。外部的类或者函数想要访问就必须给予它权利,也就是设置成该类的友元(friend)。

#include
#include
using namespace std;
class currency
{
    //建立友元
    friend ostream& operator<<(ostream& out, const currency& x);
public:
    currency(int init = 0)
    {
        amount = init;
    }
    currency &increase(const currency& x)
    {
        amount += x.amount;
        return *this;
    }
    /*void output(ostream& out) const
    {
        int theAmount = amount;
        int dollars = theAmount / 100;
        out << '$' << dollars << ".";
        int cents = theAmount - dollars * 100;
        if (cents < 10) out << '0';
        out << cents;
    }*/
    currency operator+(const currency &x) const
    {
        currency d;
        d.amount = amount + x.amount;
        return d;
    }
    currency& operator+=(const currency &x)
    {
        amount += x.amount;
        return *this;
    }
private:
    int amount;

};

//友元函数
ostream& operator<<(ostream& out, const currency& x)
{
    /*x.output(out);*/
    int theAmount = x.amount; //因为是友元,所以才能访问x的私有数据成员amount
    int dollars = theAmount / 100;
    out << '$' << dollars << ".";
    int cents = theAmount - dollars * 100;
    if (cents < 10) out << '0';
    out << cents;
    return out;
}

int main()
{
    currency a;
    currency b(100);
    currency c;
    c = a+b;
    cout << c << endl;
    c += c;
    cout << c<
        
   
相关TAG标签
上一篇:如何实现判断浏览器版本,当浏览器版本过低时提示升级浏览器,不显示原来页面内容
下一篇:如何用PHP获取微信用户的openid和基本信息?
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站