如何访问从模板类继承的私有静态类成员
How to access private static class member inherited from a template class?
我试图访问从EventListener
模板继承的静态变量,但派生的KeyboardListener
类似乎不是EventDispatcher
的朋友。我做错了什么?
template <class T>
class EventListener
{
public:
friend class EventDispatcher;
private:
static int variable;
};
template <class T> int EventListener<T>::variable;
class KeyboardListener : EventListener<KeyboardListener> {};
class EventDispatcher {
public:
static void foo() {
// this works
std::cout << &EventListener<KeyboardListener>::variable << std::endl;
// fails to compile with:
// 'int EventListener<KeyboardListener>::variable' is private
std::cout << &KeyboardListener::variable << std::endl;
}
};
您的问题是EventListener<KeyboardListener>
是KeyboardListener
的私有基类(KeyboardListener
是使用class
标记的,从基类派生时没有指定public
关键字)。因此,从KeyboardListener
到EventListener<KeyboardListener>
的转换只能由能够访问KeyboardListener
的私有成员的人来完成,而EventDispatcher
不能。
我大胆猜测private
继承是偶然的,不是你想要的。但如果确实需要,您还必须在KeyboardListener
中将EventDispatcher
声明为好友。
类的默认继承是私有的。当你有
class KeyboardListener : EventListener<KeyboardListener> {};
您是从EventListener
私有继承的,所有EventListener
成员都是私有的。我认为你应该像一样公开继承
class KeyboardListener : public EventListener<KeyboardListener> {};
实时示例
试试这个:
class KeyboardListener : EventListener<KeyboardListener> {
friend class EventDispatcher;
};
相关文章:
- 为什么我可以通过SubBase类的公共继承方法打印出基类的私人继承成员
- 派生类调用使用非继承成员的继承函数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- C :原始成员与继承成员的优先级
- 更改继承成员的地址
- C 是否可以不继承成员
- 使用模板的继承阴影继承成员
- 继承成员功能的模板专业化
- 不允许继承成员,为什么
- 派生模板类和继承成员变量的语法谜题
- 继承成员地址的C++标准
- 多级继承成员访问
- 访问专用模板的私有/继承成员变量
- 基模板继承成员,减少所需的类型
- 继承成员函数指针
- 模板专用化类不继承成员
- C++14正在初始化类构造函数初始化列表中的继承成员
- 具有专门初始化的继承成员变量
- 模板继承成员字段
- 访问数据成员的继承成员函数