如何让继承的函数使用派生类的私有变量
解决基类函数访问派生类私有变量的问题
C++中成员变量不存在多态性,基类A的成员函数里的this->array会被编译器直接绑定到A自身的私有成员,哪怕派生类B定义了同名的array,基类函数也不会自动访问派生类的版本——同名成员变量只会被隐藏,而非“覆盖”。这就是你的代码输出1 2 6的原因:print1和print2访问的是A的数组,print3最后一行才访问B的数组。
以下是三种可行的解决方法:
方案一:用虚函数提供数组访问接口
通过纯虚函数让派生类暴露自己的数组,基类函数通过虚函数间接访问派生类私有变量,利用动态绑定实现多态:
#include <iostream> class A { public: void print1() { std::cout << getArray()[0] << std::endl; } void print2() { std::cout << getArray()[1] << std::endl; } protected: // 纯虚函数,派生类必须重写以提供自身数组 virtual const int* getArray() const = 0; }; class B: public A { public: void print3() { print1(); print2(); std::cout << array[2] << std::endl; } protected: const int* getArray() const override { return array; } private: int array[3] = {4, 5, 6}; }; int main() { B b; b.print3(); // 输出4 5 6 return 0; }
方案二:将数组作为参数传递给基类函数
修改基类打印函数,让它们通过参数接收数组,派生类调用时传入自身私有数组,绕开成员变量的绑定限制:
#include <iostream> class A { public: void print1(const int arr[]) { std::cout << arr[0] << std::endl; } void print2(const int arr[]) { std::cout << arr[1] << std::endl; } }; class B: public A { public: void print3() { print1(array); print2(array); std::cout << array[2] << std::endl; } private: int array[3] = {4, 5, 6}; }; int main() { B b; b.print3(); // 输出4 5 6 return 0; }
方案三:使用CRTP静态多态
如果不需要运行时多态,可以用奇异递归模板模式(CRTP)实现静态绑定,让基类直接访问派生类成员:
#include <iostream> template<typename Derived> class A { public: void print1() { std::cout << static_cast<Derived*>(this)->array[0] << std::endl; } void print2() { std::cout << static_cast<Derived*>(this)->array[1] << std::endl; } }; class B: public A<B> { public: void print3() { print1(); print2(); std::cout << array[2] << std::endl; } private: int array[3] = {4, 5, 6}; }; int main() { B b; b.print3(); // 输出4 5 6 return 0; }
内容的提问来源于stack exchange,提问作者Skip
相关产品推荐
相关产品推荐

