C++学习 --类和对象之友元

目录

1, 全局函数做友元

2, 类做友元

3, 成员函数做友元


友元可以让函数、成员函数、类, 访问另外一个类的私有变量

1, 全局函数作友元

在类中, 通过friend 数据类型 函数名()方式将函数当着类的友元, 全局函数就可访问类的私有属性

#include <iostream>
#include <string>

using namespace std;

class Person
{
	//通过friend修饰全局函数为友元, 可通过test函数访问Person类的私有属性
	friend void test();

public:
	Person(int age):m_age(age) {};

private:
	int m_age;
};

void test()
{
	Person p(10);
	//因为test已声明为Person类的友元, 所以可以在类外部访问类的私有属性
	cout << p.m_age << endl;
}

int main()
{
	test();

	system("pause");

	return 0;
}

2, 类做友元

在类中, 通过friend class 类名方式,将类作为另外一个类的友元

#include <iostream>
#include <string>

using namespace std;

class PersonB
{
	//声明A类是B类的友元
	friend class PersonA;
public:
	PersonB(int age)
	{
		m_age = age;
	}

private:
	int m_age;
};

class PersonA
{
public:
	void func(PersonB b1)
	{
		//由于b是A的友元, 所以可以在A中访问B的私有属性
		cout << b1.m_age << endl;
	}
};

void test()
{
	PersonA a;
	PersonB b(10);
	a.func(b);
}

int main()
{
	test();

	system("pause");

	return 0;
}

3, 成员函数做友元

通过friend 数据类型 类::成员函数(), 可声明一个类的成员函数是另外一个类的友元

#include <iostream>
#include <string>

using namespace std;


class PersonB;

class PersonA
{
public:
	void func();
};

class PersonB
{
	//声明类A的func函数是B类的友元
	friend void PersonA::func();
public:
	PersonB(int age) :m_age(age) {}
private:
	int m_age;
};

//注意, 若要使用类B, 必须先定义, 不然不能使用
void PersonA::func()
{
	PersonB b1(10);
	cout << b1.m_age << endl;
}

void test()
{
	PersonA a;
	a.func();
}

int main()
{
	test();

	system("pause");

	return 0;
}

说明:若要在一个类中, 使用其他类,那么其他类必须要先定义

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值