C++ 友元

类可以允许其他类或函数访问它的非公有成员,方法是令其他类或函数成为它的友元(friend)。

应用对象: 函数 ——- 友员函数
类 ——- 友员类

功 能:提供了在类的外部访问类中的
所有成员的途径

弊 端:一定程度上破坏了类的封装性

备 注:友员关系不受类中访问修饰符的限制

1.友元函数

class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
//声明 show() 是Test的友元函数
friend void show(Test &t);
};

void show(Test &t)
{
cout << “t.m_data = ” << t.m_data << endl;
return;
}

int main(int argc,char *argv[])
{
Test t(123);
show(t);
return 0;
}

2.友元类

class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}

//声明Brother是Test的友元类
friend class Brother;

};

class Brother
{
public:
Brother(){}
~Brother(){}

void show(Test &t)
{
    cout << "t.m_data = " << t.m_data << endl;
    return;
}

};

int main(int argc,char *argv[])
{
Test t(123);
Brother b;
b.show(t);
return 0;
}

3.友元类间的关系

友员类性质:1.不能继承 - 父亲的朋友不是你的朋友
  2.不能传递 - 朋友的朋友不是你的朋友
  3.不能反转 - 你的就是我的,但是我的还是我的
class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
friend class Father;
friend class Brother;
void show(Test &t)
{
cout << “Test data=” << t.m_data << endl;
return;
}
};

class Brother
{
public:
Brother(){}
~Brother(){}
friend class Son;
};

class Father
{
public:
Father(){}
~Father(){}

void show(Test &t)
{
    cout << "Father data=" << t.m_data << endl;
    return;
}

};

class Son:public Father
{
public:
Son(){}
~Son(){}

void show(Test &t)
{
    cout << "Son data=" << t.m_data << endl;
    return;
}

};

int main(int argc,char *argv[])
{
Test t(123);
Father f;
f.show(t);
// Son s;
// s.show(t);  //error
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值