【问题标题】:How to access private static class member inherited from a template class?如何访问从模板类继承的私有静态类成员?
【发布时间】:2016-01-28 07:47:29
【问题描述】:

我正在尝试访问从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; 
        }
};

【问题讨论】:

    标签: c++ class templates friend


    【解决方案1】:

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

    class KeyboardListener : EventListener<KeyboardListener> {};
    

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

    class KeyboardListener : public EventListener<KeyboardListener> {};
    

    Live Example

    【讨论】:

    • 谢谢,这正是我所需要的。
    【解决方案2】:

    您的问题是EventListener&lt;KeyboardListener&gt;KeyboardListener私有 基类(KeyboardListener 是使用class 标出的,并且您在派生时没有指定public 关键字来自基类)。所以KeyboardListenerEventListener&lt;KeyboardListener&gt;的转换只能由可以访问KeyboardListener的私有成员的人完成,而EventDispatcher不能。

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

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

      • 这行得通,但没有更好的方法吗?我真的不想手动为每个实例加好友。
      • @user3129763,我认为@Angew 的答案可能是您想要的。也许你需要public 推导。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 2013-02-12
      相关资源
      最近更新 更多