[英]accessing non-template base class virtual function from template derived class
I'm trying to understand the template and inheritance. 我试图了解模板和继承。 I have a base class as follows:
我有一个基类如下:
class Base
{
public:
virtual ~Base() {}
virtual void setId(u_int8_t id)
{
m_id = id;
}
private:
u_int8_t m_id;
};
and a derived template class as follows: 以及派生的模板类,如下所示:
template <typename T>
class Data : public Base
{
public:
virtual void setId(u_int8_t id)
{
this->setId(id);
}
inline void setData(const T& data)
{
m_data = data;
}
inline T& data()
{
return m_data;
}
private:
T m_data;
};
this code compiles fine but crashes at run time. 此代码可以正常编译,但在运行时崩溃。 Why is this happening?
为什么会这样呢?
You get a stack overflow because setId
keeps calling itself. 由于
setId
不断调用自身,因此会导致堆栈溢出。 To call the setId
in the base class, use 要在基类中调用
setId
,请使用
virtual void setId(u_int8_t id)
{
Base::setId(id);
}
This function: 该功能:
virtual void setId(u_int8_t id)
{
this->setId(id);
}
It is calling itself recursively, until the process runs out of stack space and you get a crash. 它以递归方式调用自己,直到进程用尽堆栈空间并导致崩溃。
To call a function from the base-class you have to use the scope operator: 要从基类中调用函数,必须使用范围运算符:
Base::setId(id);
The setId()
function recursively calls itself forever. setId()
函数永远递归调用自己。 You want: 你要:
virtual void setId(u_int8_t id)
{
Base::setId(Id);
}
You don't actually need setId(u_int8_t id)
in Data
. 实际上,您在
Data
不需要setId(u_int8_t id)
。 The method is inherited from Base
. 该方法是从
Base
继承的。 If you are intending to provide a different implementation in derived class, and use in this different implementation the implementation of the Base
, then use Base::setId(id)
(as Joachim Pileborg pointed out) 如果您正打算提供派生类不同的实现,并使用在此不同实施的实施
Base
,然后利用Base::setId(id)
如约阿希姆Pileborg指出)
PS: Actually, there is nothing specific to templates in your question. PS:实际上,您的问题中没有专门针对模板的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.