C++访问控制与友元
核心原则:基于类而非对象。
1、c++的访问控制是类级别的,而不是对象级别的。
class MyClass { private: int secret; public: // ✅ 可以访问任何 MyClass 对象的私有成员 void accessOther(MyClass& other) { this->secret = 10; // 自己的 other.secret = 20; // 其他对象的 - 完全合法! } }; int main() { MyClass obj1, obj2; obj1.accessOther(obj2); // ✅ 编译通过 }2、不同类之间的访问规则:不能访问,友元破例。
class ClassA { private: int data; }; class ClassB { private: int value; public: void tryAccess(ClassA& a) { a.data = 10; // ❌ 错误!ClassB 不能访问 ClassA 的私有成员 } };class ClassA { private: int secret; // 声明 ClassB 为友元 friend class ClassB; }; class ClassB { public: void accessClassA(ClassA& a) { a.secret = 100; // ✅ 可以!因为是友元 } };3、模板实例是不同的类型
template<typename T> class Box { private: T content; public: void show(const Box<T>& other) { // 不需要友元:Box<int> 访问 Box<int> - 同一个类型 this->content = other.content; // ✅ } // 问题:Box<int> 访问 Box<double> template<typename U> void copyFrom(const Box<U>& other) { // ❌ 错误!Box<int> 不能访问 Box<double> 的私有成员 this->content = other.content; } };解决方案:模板友元
template<typename T> class Box { private: T content; // 关键:声明所有 Box<U> 都是友元 template<typename U> friend class Box; public: template<typename U> void copyFrom(const Box<U>& other) { // ✅ 现在可以了!友元声明让所有实例互通 this->content = other.content; } // 拷贝构造函数模板 template<typename U> Box(const Box<U>& other) : content(other.content) {} };