類的私有成員默認不可被外部訪問。friend 關鍵字授予特定函數或類「友元」身份,可直接訪問私有/保護成員。破壞封裝,慎用。
class Point {
double x, y;
public:
Point(double a, double b) : x(a), y(b) {}
friend double Distance(const Point&, const Point&); // 類內聲明
};
double Distance(const Point& a, const Point& b) {
double dx = a.x - b.x; // 直接訪問私有成員
double dy = a.y - b.y;
return sqrt(dx*dx + dy*dy);
}
friend,類外定義不加this 指標class A {
int x; static int y;
friend class B; // 整個 B 類是 A 的友元
public:
void set(int v) { x = v; }
void show() { cout << "x=" << x << ", y=" << y << endl; }
};
class B {
A a;
public:
B(int i, int j) { a.x = i; A::y = j; } // 訪問 A 的私有靜態成員
void show() { cout << "x=" << a.x << ", y=" << A::y << endl; }
};
類名::靜態成員 訪問#include <iostream>
using namespace std;
class Base {
int a1; protected: int a2; private: int a3;
public:
friend void friend_func(Base&);
friend class FriendClass;
};
void friend_func(Base& b) {
b.a1 = 1; b.a2 = 2; b.a3 = 3; // 全部可訪問
}
class FriendClass {
Base b;
public:
void test() { b.a1=10; b.a2=20; b.a3=30; }
};
int main() {
Base obj;
friend_func(obj);
FriendClass fc; fc.test();
return 0;
}
getter/setter 而非友元operator<<, operator+ 等需訪問私有時常用友元