怎么在C++中實(shí)現(xiàn)一個(gè)友元類

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)怎么在C++中實(shí)現(xiàn)一個(gè)友元類,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

創(chuàng)新互聯(lián)建站是一家專業(yè)提供金川企業(yè)網(wǎng)站建設(shè),專注與成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、成都外貿(mào)網(wǎng)站建設(shè)、H5場(chǎng)景定制、小程序制作等業(yè)務(wù)。10年已為金川眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站建設(shè)公司優(yōu)惠進(jìn)行中。

C++中的友元既可以實(shí)現(xiàn)友元函數(shù),也可以實(shí)現(xiàn)友元類,也就是說一個(gè)類也可以作為另外一個(gè)類的友元。當(dāng)作為一個(gè)類的友元時(shí),它的所有成員函數(shù)都是另一個(gè)類的友元函數(shù),都可以訪問另一個(gè)類的私有或者公有成員。

#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

上述就是小編為大家分享的怎么在C++中實(shí)現(xiàn)一個(gè)友元類了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

新聞名稱:怎么在C++中實(shí)現(xiàn)一個(gè)友元類
文章轉(zhuǎn)載:http://bm7419.com/article10/jjdpgo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站軟件開發(fā)、App設(shè)計(jì)、網(wǎng)站制作網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)