国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

關于C++友元類的實現(xiàn)講解

2020-01-26 13:36:46
字體:
來源:轉載
供稿:網(wǎng)友

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

總結

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網(wǎng)的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 水富县| 闻喜县| 虞城县| 诸暨市| 长沙市| 道真| 堆龙德庆县| 潞城市| 博爱县| 永川市| 金秀| 防城港市| 永昌县| 东源县| 来宾市| 泰顺县| 拉萨市| 临朐县| 卢湾区| 吐鲁番市| 毕节市| 安图县| 通山县| 彰化市| 兰溪市| 洛阳市| 蕉岭县| 平湖市| 梁平县| 上思县| 红原县| 吴旗县| 洛川县| 师宗县| 蒙山县| 晴隆县| 连南| 平陆县| 峨边| 茂名市| 尼玛县|