友員函數(shù)和友員類(lèi)

#include<iostream>

成都創(chuàng)新互聯(lián)公司專(zhuān)業(yè)為企業(yè)提供安鄉(xiāng)網(wǎng)站建設(shè)、安鄉(xiāng)做網(wǎng)站、安鄉(xiāng)網(wǎng)站設(shè)計(jì)、安鄉(xiāng)網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、安鄉(xiāng)企業(yè)網(wǎng)站模板建站服務(wù),10年安鄉(xiāng)做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。

using namespace std;

class Test2//注意友員類(lèi)的定義放在Test1的之上!!

{

friend class Test1;//Test1想直接訪(fǎng)問(wèn)Test2的private參數(shù),所以聲明為我是你的朋友!

public:

Test2(int a, int b){ x = a; y = b; }

int getx(){

return x;

}

int gety(){

return y;

}

private:

int x, y;

};

class Test1{

public:

Test1(int a, int b) :t(a, b){}

void print(){ cout << "Test2 的對(duì)象t的x:" << t.x << endl; }

private:

Test2 t;//因?yàn)門(mén)est2是Test1的友員

};

class Test3{

public:

friend int getTx(Test3 & t3);//友員函數(shù)通過(guò)類(lèi)的指針或引用訪(fǎng)問(wèn)這個(gè)類(lèi)對(duì)象的私有成員

private:

//friend int getTx(Test3 & t3);//放在這里完全一樣,訪(fǎng)問(wèn)限制符對(duì)友員函數(shù)不管用

int x;

};

int getTx(Test3 & t3){//友員函數(shù)在類(lèi)外定義!不加static防止給別的混淆

return t3.x;//友員函數(shù)可以使用類(lèi)的所有函數(shù)

}

int main(){

Test1 t1(2,5);

t1.print();

system("pause");

return 0;

}

網(wǎng)站題目:友員函數(shù)和友員類(lèi)
文章地址:http://muchs.cn/article32/ihidpc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、網(wǎng)站建設(shè)、品牌網(wǎng)站制作網(wǎng)站導(dǎo)航、品牌網(wǎng)站設(shè)計(jì)、域名注冊(cè)

廣告

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

網(wǎng)站優(yōu)化排名