java 友元_C++ 友元函数 | 菜鸟教程
對(duì)教程中的例子,稍加修改,添加了友元類的使用。
#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;
}
};
// 成員函數(shù)定義
void Box::setWidth(double wid)
{
width = wid;
}
// 請(qǐng)注意:printWidth() 不是任何類的成員函數(shù)
void printWidth(Box box)
{
/* 因?yàn)?printWidth() 是 Box 的友元,它可以直接訪問該類的任何成員 */
cout << "Width of box : " << box.width << endl;
}
// 程序的主函數(shù)
int main()
{
Box box;
BigBox big;
// 使用成員函數(shù)設(shè)置寬度
box.setWidth(10.0);
// 使用友元函數(shù)輸出寬度
printWidth(box);
// 使用友元類中的方法設(shè)置寬度
big.Print(20, box);
getchar();
return 0;
}
Mr.Right
Mr.Right
826***410@qq.com2年前 (2019-03-08)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的java 友元_C++ 友元函数 | 菜鸟教程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java.util.set cannot
- 下一篇: 推到 旋转矩阵公式_想知道旋转矩阵的带入