關于C++友元類的實現(xiàn)講解
更新時間:2018年12月20日 09:33:37 作者:Engineer-Bruce_Yang
今天小編就為大家分享一篇關于關于C++友元類的實現(xiàn)講解,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
C++中的友元既可以實現(xiàn)友元函數(shù),也可以實現(xiàn)友元類,也就是說一個類也可以作為另外一個類的友元。當作為一個類的友元時,它的所有成員函數(shù)都是另一個類的友元函數(shù),都可以訪問另一個類的私有或者公有成員。
請看實例:
#include <iostream> #include <cstring> using namespace std ; //聲明教師類 class Techer ; //學生類 class Student { private: string name ; int age ; char sex ; int score ; public : Student(string name , int age , char sex , int score); void stu_print(Techer &tech); }; //教師類 class Techer { private: string name ; int age ; char sex ; int score ; public : Techer(string name , int age , char sex , int score); //聲明一個友元類 friend Student ; }; //Student類的構造函數(shù)的實現(xiàn) Student::Student(string name , int age , char sex , int score) { this->name = name ; this->age = age ; this->sex = sex ; this->score = score ; } //Techer類的構造函數(shù)的實現(xiàn) Techer::Techer(string name , int age , char sex , int score) { this->name = name ; this->age = age ; this->sex = sex ; this->score = score ; } //打印Student類中的私有成員和Techer的私有成員 void Student::stu_print(Techer &tech) { //用this指針訪問本類的成員 cout << this->name << endl ; cout << this->age << endl ; cout << this->sex << endl ; cout << this->score << endl ; //訪問Techer類的成員 cout << tech.name << endl ; cout << tech.age << endl ; cout << tech.sex << endl ; cout << tech.score << endl ; } int main(void) { Student stu1("YYX",24,'N',86); Techer t1("hou",40,'N',99); stu1.stu_print(t1); return 0 ; }
運行結果:
YYX
24
N
86
hou
40
N
99
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
C++實現(xiàn)LeetCode(128.求最長連續(xù)序列)
這篇文章主要介紹了C++實現(xiàn)LeetCode(128.求最長連續(xù)序列),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07