雷火电竞-中国电竞赛事及体育赛事平台

歡迎來(lái)到入門(mén)教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

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

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊:

C++中的友元既可以實(shí)現(xiàn)友元函數(shù),也可以實(shí)現(xiàn)友元類,也就是說(shuō)一個(gè)類也可以作為另外一個(gè)類的友元。當(dāng)作為一個(gè)類的友元時(shí),它的所有成員函數(shù)都是另一個(gè)類的友元函數(shù),都可以訪問(wèn)另一個(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指針訪問(wèn)本類的成員 
 cout << this->name << endl ; 
 cout << this->age << endl ; 
 cout << this->sex << endl ; 
 cout << this->score << endl ;
 //訪問(wèn)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)鏈接

上一篇:實(shí)戰(zhàn)開(kāi)發(fā)為單片機(jī)的按鍵加一個(gè)鎖防止多次觸發(fā)的細(xì)節(jié)

欄    目:C語(yǔ)言

下一篇:C語(yǔ)言字符串另類用法的實(shí)現(xiàn)

本文標(biāo)題:關(guān)于C++友元類的實(shí)現(xiàn)講解

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/610.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有