一、友元函式
- 友元實際上并不是面向物件的特征,而是為了兼顧C語言程式設計的習慣與C++友元的概念破壞了類的封裝性和資訊隱藏,但有助于資料共享,能夠提高程式執行的效率,資訊隱藏的特點,而特意增加的功能,這是一種類成員的訪問權限,
- 友元使用關鍵字friend標識,在類定義中,當friend出現在函式說明陳述句的前面時,表示該函式為類的友元函式,一個函式可以同時說明為多個類的友元函式,一個類中也可以有多個友元函式,當friend出現在類名之前時,表示該類為類的友元類,
- 友元函式可以訪問當前類中的所有成員,包括 public、protected、private 屬性的,
- 友元函式不是類的成員函式,但允許訪問類中的所有成員,在函式體中訪問物件成員時,必須使用“物件名.物件成員名”的方式,
#include<iostream> using namespace std; class Student{ private: int id; string name; public: Student(int id,string name); //宣告友元函式 friend void show(Student &stu); }; //友元函式的實作(直接可以訪問類的私有屬性) void show(Student &stu){ cout<< stu.id << " name:" <<stu.name <<endl; }; Student::Student(int id,string name):id(id),name(name){ } int main(){ Student stu(1,"張三"); show(stu); return 0; }
二、友元類
- 如果將一個類B說明為另一個類A的友元類,則類B中的所有函式都是類A的友元函式,在類B的所有成員函式中都可以訪問類A中的所有成員,在類定義中
- 宣告友元類的格式如下:friend class 類名;
- 友元類的關系是單向的,若說明類B是類A的友元類,不等于類A也是類B的友元類,友元類的關系不能傳遞,即若類B是類A的友元類,而類C是類B的友元類,不等于類C是類A的友元類,除非確有必要,一般不把整個類說明為友元類,而僅把類中的某些成員函式說明為友元函式,
#include<iostream> using namespace std; class Teacher; class Student{ private: int id; string name; public: Student(int id,string name); void show(Teacher *tea); }; Student::Student(int id,string name):id(id),name(name){ } class Teacher{ private: int id; string name; public: Teacher(int id,string name); //將Student類宣告為Teacher類的友元類 friend class Student; }; Teacher::Teacher(int id,string name):id(id),name(name){ } void Student::show(Teacher *tea){ cout << this->id << this->name << tea->name << endl; } int main(){ Teacher tea(1,"老外"); Student stu(1,"張三"); stu.show(&tea); return 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20785.html
標籤:C++
上一篇:有大神知道這個該怎么辦嗎?
