继承类中别名常量报错:子类无法引用基类protected静态常量
问题解析与解决方案
编译器判定逻辑
C++的访问控制看的是访问路径,而非成员的原始权限:
- Base里的
A_是protected,原本Base的子类(比如Foo)和子类的子类(比如Go)都能通过继承链访问它。 - 但Foo中用
using Base::A_把这个成员的权限改成private后,相当于在Foo的作用域内把A_封装成了自己的private成员。 - Go是Foo的子类,访问
Base::A_的路径是Go -> Foo -> Base,这条路径上Foo已经把A_设为private,所以编译器会判定Go无权访问Foo的private成员——哪怕A_在Base里是protected的。
解决方案
方案1:修改Foo中using声明的权限
如果允许Foo的子类访问A_,直接把Foo里的private: using Base::A_;改成protected即可:
class Base { protected: static const int A_ = 10; }; class Foo : public Base { protected: using Base::A_; }; class Go : public Foo { public: void func() { int x = A_; // 正常访问 } };
方案2:在Foo中提供间接访问接口
如果不想改动A_在Foo中的直接权限,可以在Foo里加一个protected的静态接口,让Go通过这个接口获取A_的值:
class Base { protected: static const int A_ = 10; }; class Foo : public Base { private: using Base::A_; protected: static int getA() { return A_; } }; class Go : public Foo { public: void func() { int x = getA(); // 通过接口访问 } };
方案3:让Go直接继承Base(按需使用)
如果类结构允许,让Go直接继承Base,就能绕过Foo的权限限制直接访问Base::A_:
class Base { protected: static const int A_ = 10; }; class Foo : public Base { private: using Base::A_; }; class Go : public Base, public Foo { public: void func() { int x = Base::A_; // 直接访问Base的protected成员 } };
内容的提问来源于stack exchange,提问作者kstn
相关产品推荐
相关产品推荐

