#include <iostream>
using namespace std;
class test{
private:
int a;
int b;
public:
test(int a = 1, int b = 2){
this->a = a;
this->b = b;
}
int re(test ccc){
a = ccc.a + 444;
b = ccc.b + 444;
}
};
为什么re函数中的ccc可以直接调用a和b而不报错?
搜尋了下(關鍵字:c++存取類別私有變數),這裡有不錯的解釋:
http://stackoverflow.com/questions/7396846/with-a-private-modifier-why-can-the-member-in-other-objects-be-accessed-directl
因為 C++ 中一個類別是自己這個類別的友元(friend class)。
因為 a,b 都是 test 類別的成員。
一個類別的方法可以存取自己的私有成員
同一類別的不同物件間可以互相存取私有成員
一個類別當然可以
私有資料不能直接訪問,只能透過類別的成員函數和友元函數呼叫。
友元函數 http://learn.jser.com/cplusplus/cpp-friend-functions.html