gpt4 book ai didi

c++ - 如何访问从模板类继承的私有(private)静态类成员?

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:24 25 4
gpt4 key购买 nike

我正在尝试访问从 EventListener 继承的静态变量模板,但它看起来像派生的 KeyboardListener类不是 EventDispatcher 的 friend .我做错了什么?

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私有(private)基类( KeyboardListener 是使用 class 贴标的,并且您在从基类派生时没有指定 public 关键字)。所以从 KeyboardListener 的转换至 EventListener<KeyboardListener>只能由可以访问 KeyboardListener 的私有(private)成员的人完成,这EventDispatcher不能。

我敢猜测 private继承是偶然的,而不是你想要的。但如果确实需要,则必须声明 EventDispatcher作为 friend KeyboardListener

关于c++ - 如何访问从模板类继承的私有(private)静态类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33392714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com