c++基礎複習——友元

在程序中,有時候我們需要類外的特殊函數或者類也可以訪問私有熟悉,這時候就要友元技術

友元的目的就是讓一個函數或者類能夠訪問另一個類中的私有成員。

友元的三種實現:

  • 全局函數做友元
  • 類做友元
  • 成員函數做友元
#include <iostream>
#include <string>
using namespace std;

/*成員函數做友元*/
class myfriend2
{
public:
	myfriend2();
	void visit2();
	void visit3();
	Home* p;
};

myfriend2::myfriend2()
{
	this->p = new(Home);
}

void myfriend2::visit2()
{
	cout << "i'm visiting " << p->A << endl;
}

void myfriend2::visit3()
{
	cout << "i'm visiting " << p->B << endl;
}

/*主要的類*/
class Home
{
	friend void test1();  //全局函數做友元
	friend class myfriend; //類作爲友元
	friend void myfriend2::visit3(); //成員函數做友元(記住此時的myfriend2類必須定義在前面,不然就是隻有聲明而沒有定義)
public:
	Home(string a, string b);
	string A;
private:
	string B;
};

Home::Home(string a = "sittingroom", string b = "bedroom"): A(a), B(b) {} //提供了有參構造函數,不會再提供無參構造函數

class myfriend
{
public:
	myfriend();
	void visit();
	Home* p;
};

/*類做友元*/
myfriend::myfriend()
{
	this->p = new(Home);
}

void myfriend::visit()
{
	cout << "i'm visiting " << p->A << endl;
	cout << "i'm visiting " << p->B << endl;
}

/*全局函數做友元*/
void test1()
{
	Home p;

	cout << "home's a is " << p.A << endl;
	cout << "home's b is " << p.B << endl;
}

void test2()
{
	myfriend p;
	p.visit();
}

void test3()
{
	myfriend2 p;
	p.visit2();
	p.visit3();
}

int main()
{
	test1();
	test2();
	test3();

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章