友元的三种实现

友元的三种实现

  • 全局函数做友元
  • 类做友元
  • 成员函数做友元
#include 
#include 
using namespace std;


//友元的三种实现
//
//* 全局函数做友元
//* 类做友元
//* 成员函数做友元

class Building
{
	//告诉编译器 goodGay全局函数 是 Building类的好朋友,
	//可以访问类中的私有内容
	friend void goodGay(Building* building);
public:
	Building()
	{
		m_S = "客厅";
		m_B = "卧室";
	}
public:
	string m_S;
private:
	string m_B;
};

void goodGay(Building* building)
{
	cout << "好基友正在访问:" << building->m_S << endl;
	cout << "好基友正在访问:" << building->m_B << endl;

}
void test01()
{
	Building b;
	goodGay(&b);
}

int main()
{
	test01();
	return 0;
}

类做友元

#include 
#include 
using namespace std;


//友元的三种实现
//
//* 全局函数做友元
//* 类做友元
//* 成员函数做友元
class Building;
class goodGay
{

public:
	goodGay();
	void visit();

private:
	Building* building;
};

class Building
{
	//告诉编译器goodGay类是Building类的好朋友,可以访问到Building类中的私有内容
	friend class goodGay;
public:
	Building();
public:
	string m_S;
private:
	string m_B;
};

Building::Building()
{
	m_S = "客厅";
	m_B = "卧室";
}

goodGay::goodGay()
{
	building = new Building;
}
void goodGay::visit()
{
	cout << "好基友正在访问" << building->m_S << endl;
	cout << "好基友正在访问" << building->m_B << endl;
}

void test01()
{
	goodGay gg;
	gg.visit();
}

int main()
{
	test01();
	return 0;
}

成员函数做友元

#include 
#include 
using namespace std;


//友元的三种实现
//
//* 全局函数做友元
//* 类做友元
//* 成员函数做友元
class Building;
class goodGay
{

public:
	goodGay();
	void visit();
	void visit2();

private:
	Building* building;
};

class Building
{
	//告诉编译器goodGay类是Building类的好朋友,可以访问到Building类中的私有内容
	friend void goodGay::visit();
	//friend void goodGay::visit2();

public:
	Building();
public:
	string m_S;
private:
	string m_B;
};

Building::Building()
{
	m_S = "客厅";
	m_B = "卧室";
}

goodGay::goodGay()
{
	building = new Building;
}
void goodGay::visit()
{
	cout << "好基友正在访问" << building->m_S << endl;
	cout << "好基友正在访问" << building->m_B << endl;
}
void goodGay::visit2()
{
	cout << "好基友正在访问" << building->m_S << endl;
	//cout << "好基友正在访问" << building->m_B << endl; //-- 没有友元,没法访问
}
void test01()
{
	goodGay gg;
	gg.visit2();
}

int main()
{
	test01();
	return 0;
}

你可能感兴趣的:(C,c++,开发语言)