C++ 友元类,友元函数

//友元函数  友元类
#include<iostream>
using namespace std;



class PointB
{
public:
    friend class PointC;
    //类PointC是类PointB的友元类--意味着类PointC对象可以调用PointB中所有的成员
    void Test(){
        ;
    }
private:
    int x;
    int y;
};

class PointC
{
public:
    void printfPointB(){
        //调用其友元类的私有属性
        cout << pb.y << endl;
        //调用PointB的成员函数
        pb.Test();
    }
private:
    PointB pb;
};


class PointA
{
public:
    //友元函数
    friend void Friendfun(PointA* pin);
    int GetA(){
        return a;
    }
    int GetB(){
        return b;
    }
private:
    int a;
    int b;
};

//friend 关系户
//const(C语言)冒牌货
//register cpu身边的小太监(寄存器)
//typedef 混号王(起别名)


//友元函数
//友元必须有一个参数,就是友元函数所在类的对象指针(不然无法访问对象的私有属性)
//友元函数是一个全局函数
//友元函数破坏类的封装性
void Friendfun(PointA* pin){
    //可以直接访问类的私有成员
    pin->a = 10;
    pin->b = 20;
}


void protectA(){
    PointA *p1 = new PointA();
    Friendfun(p1);
    cout << "a=" << p1->GetA() << ";b=" << p1->GetB() << endl;
    if (p1!=NULL)
    {
        delete p1;
    }
}

void main(){
    protectA();
    system("pause");
}

 

posted on 2016-06-24 09:59  寒魔影  阅读(198)  评论(0编辑  收藏  举报

导航