Commit e2de3e3f authored by Clark Lin's avatar Clark Lin
Browse files

add friend function

parent 9c483d7e
#include <iostream>
using namespace std;
class Box {
private:
double width;
public:
double length;
// 类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。
// 尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
friend void printWidth(Box box) {
// 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员
cout << "Width of box : " << box.width <<endl;
};
void setWidth(double width) {
this->width = width;
};
};
// 程序的主函数
int main() {
Box box;
// 使用成员函数设置宽度
box.setWidth(10.0);
// 使用友元函数输出宽度
printWidth(box);
return 0;
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment