友元函數是 C++ 中打破類封裝性的特殊機制。它允許非成員函數訪問類的 private 和 protected 成員。關鍵特性:
friend 關鍵字聲明this 指針題目要求:兩個類 shen_stock 和 shang_stock,各自擁有三個私有成員(普通股、ST股、PT股)。需求:
count() 計算兩市總和#include <iostream>
using namespace std;
// 前向聲明
class shang_stock;
class shen_stock {
int general, st, pt;
public:
shen_stock(int g, int s, int p) : general(g), st(s), pt(p) {}
friend void add_shen(shen_stock &s); // 深圳專用友元
friend void count(shen_stock &s, shang_stock &ss); // 共享友元
};
class shang_stock {
int general, st, pt;
public:
shang_stock(int g, int s, int p) : general(g), st(s), pt(p) {}
friend void add_shang(shang_stock &s); // 上海專用友元
friend void count(shen_stock &s, shang_stock &ss); // 共享友元
};
// 深圳市場統計
void add_shen(shen_stock &s) {
cout << "shen_stock total: " << s.general + s.st + s.pt << endl;
}
// 上海市場統計
void add_shang(shang_stock &s) {
cout << "shang_stock total: " << s.general + s.st + s.pt << endl;
}
// 兩市合計
void count(shen_stock &s, shang_stock &ss) {
int total = s.general + s.st + s.pt + ss.general + ss.st + ss.pt;
cout << "Total stocks: " << total << endl;
}
int main() {
shen_stock sz(100, 20, 5);
shang_stock sh(80, 15, 3);
add_shen(sz);
add_shang(sh);
count(sz, sh);
return 0;
}
class shang_stock;)friend void count(...)shen_stock::)友元雖然強大,但會破壞封裝性。原則上:
operator<<)、緊密協作的類之間、或極少數性能關鍵場景使用