Friend Function
Friend function นิยามนอกคลาส แต่เข้าถึง private/protected members ได้ทั้งหมด Prototype อยู่ใน class definition แต่ ไม่ใช่ member function
Friend สามารถเป็น
- Function / Function template
- Member function
- Class / Class template (ทั้งคลาสและสมาชิกทั้งหมดเป็น friend)
การประกาศ
class Box {
double width;
public:
double length;
friend void printWidth(Box box); // friend function
void setWidth(double wid);
};
Friend Class
friend class ClassTwo;
วางใน ClassOne เพื่อให้ ClassTwo เข้าถึง private/protected ของ ClassOne ได้
ตัวอย่างสมบูรณ์
#include <iostream>
using namespace std;
class Box {
double width;
public:
friend void printWidth(Box box);
void setWidth(double wid);
};
void Box::setWidth(double wid) { width = wid; }
void printWidth(Box box) {
cout << "Width of box: " << box.width << endl;
}
int main() {
Box box;
box.setWidth(10.0);
printWidth(box);
return 0;
}
ผลลัพธ์
Width of box: 10
แม้ไม่ใช่ member function แต่เข้าถึง private member ได้ มีประโยชน์ในบางสถานการณ์
หมายเหตุ: เนื้อหานี้ซ้ำกับ ID 1004083474