我有这个
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
如何正确构建对象?
答案 0 :(得分:2)
您需要指定模板参数:
self.view.frame.size.width
修改强>
对于链接错误,请尝试将定义移动到头文件。
请参阅Why can templates only be implemented in the header file?
答案 1 :(得分:0)
我看到了几个错误。
错误1
template<class PayloadType>
Event<PayloadType>::Event(PayloadType payload) {
// this->payload is of type PayloadType*
// payload is of type PayloadType
// Assigning to a pointer using an object is a problem.
this->payload = payload;
}
最简单的决议是让this->payload
成为PayloadType
类型的对象。
错误2
在使用派生类中的基类构造函数时,您没有使用模板参数。
SimpleEvent(PayloadType payload) : Event(payload) { }
需要:
SimpleEvent(PayloadType payload) : Event<PayloadType>(payload) { }
<强>更新强>
自这个答案以来,OP的问题已经更新。因此,第一个错误不再是错误。