365真正的官网-beat365体育登陆网址-365bet.com

— 怀旧经典 · 永恒记忆 —

C++友元函数

C++友元函数

对教程中的例子,稍加修改,添加了友元类的使用。

#include

using namespace std;

class Box

{

double width;

public:

friend void printWidth(Box box);

friend class BigBox;

void setWidth(double wid);

};

class BigBox

{

public :

void Print(int width, Box &box)

{

// BigBox是Box的友元类,它可以直接访问Box类的任何成员

box.setWidth(width);

cout << "Width of box : " << box.width << endl;

}

};

// 成员函数定义

void Box::setWidth(double wid)

{

width = wid;

}

// 请注意:printWidth() 不是任何类的成员函数

void printWidth(Box box)

{

/* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */

cout << "Width of box : " << box.width << endl;

}

// 程序的主函数

int main()

{

Box box;

BigBox big;

// 使用成员函数设置宽度

box.setWidth(10.0);

// 使用友元函数输出宽度

printWidth(box);

// 使用友元类中的方法设置宽度

big.Print(20, box);

getchar();

return 0;

}Mr.Right Mr.Right

826***410@qq.com

7年前 (2019-03-08)

相关推荐

365bet.com 迪龙usb游戏手柄驱动 官方版

迪龙usb游戏手柄驱动 官方版

📅 07-19 👁️ 3596
365真正的官网 查看class文件的3个工具JD-GUI,JD-Ecilpse,JD-IntelliJ

查看class文件的3个工具JD-GUI,JD-Ecilpse,JD-IntelliJ

📅 07-30 👁️ 4257
beat365体育登陆网址 斯通斯双响凯恩戴帽 英格兰6-1大胜巴拿马提前晋级

斯通斯双响凯恩戴帽 英格兰6-1大胜巴拿马提前晋级

📅 07-20 👁️ 5730
365真正的官网 xp更改文件图标

xp更改文件图标

📅 08-06 👁️ 1952
beat365体育登陆网址 受虐狂的意思、解释和含义

受虐狂的意思、解释和含义

📅 07-11 👁️ 4431
365bet.com 常见的剪辑手法有哪些

常见的剪辑手法有哪些

📅 07-06 👁️ 2896
365真正的官网 HIFIDIY论坛

HIFIDIY论坛

📅 07-22 👁️ 6696
365bet.com 速达天耀3000.Online PRO

速达天耀3000.Online PRO

📅 08-01 👁️ 9490
365真正的官网 【秦梧x你】一份忏悔者的自述

【秦梧x你】一份忏悔者的自述

📅 07-05 👁️ 1917
365真正的官网 美国为何没有一条高铁建成通车?

美国为何没有一条高铁建成通车?

📅 08-04 👁️ 5672