關(guān)于C++友元類的實(shí)現(xiàn)講解
C++中的友元既可以實(shí)現(xiàn)友元函數(shù),也可以實(shí)現(xiàn)友元類,也就是說一個(gè)類也可以作為另外一個(gè)類的友元。當(dāng)作為一個(gè)類的友元時(shí),它的所有成員函數(shù)都是另一個(gè)類的友元函數(shù),都可以訪問另一個(gè)類的私有或者公有成員。
請(qǐng)看實(shí)例:
#include <iostream> #include <cstring> using namespace std ; //聲明教師類 class Techer ; //學(xué)生類 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); //聲明一個(gè)友元類 friend Student ; }; //Student類的構(gòu)造函數(shù)的實(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類的構(gòu)造函數(shù)的實(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 ; }
運(yùn)行結(jié)果:
YYX
24
N
86
hou
40
N
99
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
C++實(shí)現(xiàn)LeetCode(128.求最長(zhǎng)連續(xù)序列)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(128.求最長(zhǎng)連續(xù)序列),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C++中實(shí)現(xiàn)子進(jìn)程執(zhí)行和管道通信詳解
在這篇博客中,我們將深入探索如何在 C++ 程序中實(shí)現(xiàn)子進(jìn)程的創(chuàng)建與執(zhí)行,以及父子進(jìn)程間的管道通信,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01C語(yǔ)言實(shí)現(xiàn)車票管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)車票管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05