#include
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而不报错?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为 C++ 中一个类是自己这个类的友元(friend class)。
因为 a,b 都是 test 类的成员。
一个类的方法可以访问自己的私有成员
同一类的不同对象间可以互相访问私有成员
一个类里当然可以
私有数据不能被直接访问,只能通过类的成员函数和友元函数调用。