如何访问从模板类继承的私有静态类成员

How to access private static class member inherited from a template class?

本文关键字:继承 成员 静态类 何访问 访问      更新时间:2023-10-16

我试图访问从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关键字)。因此,从KeyboardListenerEventListener<KeyboardListener>的转换只能由能够访问KeyboardListener的私有成员的人来完成,而EventDispatcher不能。

我大胆猜测private继承是偶然的,不是你想要的。但如果确实需要,您还必须在KeyboardListener中将EventDispatcher声明为好友。

类的默认继承是私有的。当你有

class KeyboardListener : EventListener<KeyboardListener> {};

您是从EventListener私有继承的,所有EventListener成员都是私有的。我认为你应该像一样公开继承

class KeyboardListener : public EventListener<KeyboardListener> {};

实时示例

试试这个:

class KeyboardListener : EventListener<KeyboardListener> {
    friend class EventDispatcher;
};