c++学习笔记(二) 友元

c++可以为类定义友元类,友元函数,友元成员函数,允许友元访问该类的私有成员。

#include<iostream>
using namespace std;
class B
{
	friend class A;
	private:
		int topsecret;
	public:
		B(int t=0):topsecret(t){
		}
		~B(void){}
		int gettopsecret()
		{
			return topsecret;
		}
	
		
 } ;
 class A
 {
 	public:
 		A(void){
		 }
		 ~A(void) {
		 }
		 void change(B &b)const
		 {
		 	b.topsecret++;
		 }
		 
 };
 
 int main()
 {
 	B b(0);
 	A a;
 	a.change(b);
	 cout<<b.gettopsecret()<<endl; 
 }

该例可以看出,类A为类B的友元,所以A可以访问B中的私有变量topsecret,并让它的值加一。

1.友元定义可以放在类中的任何位置

2.友元类无法被继承和传递

3.定义某函数是类A的友元函数的方法是:

class A
{
    friend void f();
}

4.定义友元成员函数的方法:

class B
{
    friend void A::f();
}
发布了23 篇原创文章 · 获赞 3 · 访问量 4037

猜你喜欢

转载自blog.csdn.net/weixin_43098069/article/details/84581759