友元函数和友元类的使用 | c++ 进阶学习一条龙(一)

不用复杂长到不想看的文章,几句话,测试代码运行一遍,马上了解友元

类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。

因为友元函数不是成员函数所以没有this指针,则参数要有几种情况: 

要访问非static成员时,需要对象做参数;

要访问static成员或全局变量时,则不需要对象做参数;

#include <iostream>
#include <bits/stdc++.h> //c++万能头
using namespace std;


class Box
{
    int width;
    static int height;
public:
    void setwidth(int wid);
    //将printwidth设置为Box的友元函数,printwidth就可以访问Box类的保护成员和私有成员
    friend void printwidth(Box& box);
    friend void printheight();
    //将Bigbox设置为Box的友元类,Bigbox就可以访问Box类的保护成员和私有成员
    friend class Bigbox;
};
class Bigbox
{
public:
    void Print(Box& box,int wid);
};

int Box::height=10;

void Box::setwidth(int wid)
{
    this->width=wid;
}

void Bigbox::Print(Box &box, int wid)
{
    box.setwidth(wid);
    cout<<box.width<<endl;
}

void printwidth(Box& box)
{
    cout<<box.width<<endl;
}

void printheight()
{
    cout<<Box::height<<endl;
}


int main()
{
   Box boxt;
   boxt.setwidth(5);
   printwidth(boxt);
   printheight();//调用静态变量无需借助对象
   Bigbox bbox;
   bbox.Print(boxt,20);
   printwidth(boxt);


}

运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值