gpt4 book ai didi

子类上的 C++ 模板父类构造函数

转载 作者:行者123 更新时间:2023-11-28 02:06:38 27 4
gpt4 key购买 nike

我有这个

template<class PayloadType>
class Event {
protected:
PayloadType payload;
public:
Event(PayloadType payload);
};

这是定义:

template<class PayloadType>
Event<PayloadType>::Event(PayloadType payload) {
this->payload = payload;
}

还有这个:

class SimplePayload {
protected:
int number;
public:
SimplePayload(int number) : number(number) { }
int getNumber() { return number; };
};

template<class PayloadType>
class SimpleEvent : public Event<PayloadType> {
protected:
PayloadType payload;
public:
SimpleEvent(PayloadType payload) : Event<PayloadType>(payload) { }
};

尝试使用它:

SimplePayload simplePayload;
SimpleEvent<SimplePayload> *simpleEvent = dynamic_cast<SimpleEvent<SimplePayload>*>(new Event<SimplePayload>(simplePayload));

我收到这个错误:

error: member initializer 'Event' does not name a non-static data member or base class

如何正确构造对象?

最佳答案

您需要指定模板参数:

template<class PayloadType>
class SimpleEvent : public Event<PayloadType> {
protected:
PayloadType payload;
public:
SimpleEvent(PayloadType payload) : Event<PayloadType>(payload) { }
~~~~~~~~~~~~~
};

编辑

对于链接错误,尝试将定义移动到头文件。

参见 Why can templates only be implemented in the header file?

关于子类上的 C++ 模板父类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37212499/

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