溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2021-06-02 16:43:26 來源:億速云 閱讀:156 作者:Leah 欄目:編程語言

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

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)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI