Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Friend Class และ Friend Function ใน C++


Friend Function

Friend function ของคลาสถูกนิยามนอกขอบเขตของคลาสนั้น แต่มีสิทธิ์เข้าถึงสมาชิก private และ protected ทั้งหมด แม้ prototype จะปรากฏใน class definition แต่ friend functions ไม่ใช่ member functions

Friend สามารถเป็นได้

  • Function
  • Function template
  • Member function
  • Class หรือ class template (ทั้งคลาสและสมาชิกทั้งหมดจะเป็น friend)

การประกาศ Friend Function

class Box {
    double width;
public:
    double length;
    friend void printWidth(Box box);  // ประกาศ friend
    void setWidth(double wid);
};

การประกาศ Friend Class

friend class ClassTwo;

วางใน class ClassOne เพื่อให้ ClassTwo เข้าถึงสมาชิก private/protected ของ ClassOne ได้

ตัวอย่างสมบูรณ์

#include <iostream>
using namespace std;

class Box {
    double width;
public:
    friend void printWidth(Box box);
    void setWidth(double wid);
};

// Member function definition
void Box::setWidth(double wid) {
    width = wid;
}

// Friend function (ไม่ใช่ member ของคลาสใดๆ)
void printWidth(Box box) {
    // เข้าถึง private member width ได้โดยตรง
    cout << "Width of box: " << box.width << endl;
}

int main() {
    Box box;
    box.setWidth(10.0);
    printWidth(box);  // ใช้ friend function
    return 0;
}

ผลลัพธ์

Width of box: 10

แม้ฟังก์ชันจะไม่ใช่สมาชิกของคลาส แต่ก็เข้าถึงตัวแปรสมาชิกได้โดยตรง มีประโยชน์ในบางสถานการณ์