[英]Calling Base Class Copy Constructor in Derived Class
Just to preface, I did a lot of reading before posting because I know this is probably a very basic question, but I'm still missing something, so sorry in advance if I did... 只是作为序言,我在发布之前做了很多阅读,因为我知道这可能是一个非常基本的问题,但是我仍然缺少一些东西,所以如果这样做了,请提前抱歉...
I have a template derived class based upon another class: 我有一个基于另一个类的模板派生类:
class BaseBuffer
{
public:
// Constructor
BaseBuffer() {};
BaseBuffer(long buf_size);
BaseBuffer(const BaseBuffer& orig);
....
template <class T>
class DataBuffer : public BaseBuffer
{
....
I am implementing the copy constructor for DataBuffer
. 我正在实现DataBuffer
的副本构造函数。 I have already written the copy constructor for BaseBuffer
as shown above. 我已经为BaseBuffer
编写了复制构造函数,如上所示。
Now, as I understand, to call the copy of BaseBuffer
as DataBuffer
is being copied, I must do 现在,据我所知,要在复制DataBuffer
调用BaseBuffer
的副本,我必须
DataBuffer(const DataBuffer& orig) : BaseBuffer(orig)
{
// Initialize an array of memory given the type
buf_ = new T[size_];
....
where BaseBuffer(orig)
should, as another SO answer states, "This calls the Base copy constructor on the Base sub-object." 另一个SO答案指出, BaseBuffer(orig)
应该在其中“这将调用Base子对象上的Base复制构造函数。”
When I DON'T do this, then the expected bad thing happens: all the properties which belong to BaseBuffer
do not get copied. 当我不这样做时,就会发生预期的坏事情:不会复制属于BaseBuffer
所有属性。
When I DO do this, unexpected bad thing happens: I get an EXC_BAD_ACCESS when the code gets to the point of calling BaseBuffer(orig)
. 当我这样做时,发生了意外的坏事:当代码到达调用BaseBuffer(orig)
的地步时,我得到了EXC_BAD_ACCESS。
So this kinda does and doesn't make sense to me. 所以这对我来说是有意义的,也没有意义。 As DataBuffer
is inherited from BaseBuffer
, it makes sense that I could call the BaseBuffer
copy constructor and it would only "look" in the memory locations it knows about, and all the DataBuffer
extra stuff "fits" around the base. 由于DataBuffer
是从BaseBuffer
继承的,所以可以调用BaseBuffer
复制构造函数是有意义的,它只会“查找”它所知道的内存位置,并且所有DataBuffer
多余内容都“适合”该基数。
But on the other hand, it seems to make sense that strictly speaking, calling BaseBuffer(&<DataBuffer>)
doesn't make sense because I have only defined BaseBuffer(&<BaseBuffer>)
. 但另一方面,严格来讲,调用BaseBuffer(&<DataBuffer>)
似乎没有道理,因为我仅定义了BaseBuffer(&<BaseBuffer>)
。
So my question has two parts, 所以我的问题分为两个部分,
DataBuffer(const DataBuffer& orig) : BaseBuffer(orig) {...}
syntax (and if it's not, sorry)? 为什么使用这种“正确的” DataBuffer(const DataBuffer& orig) : BaseBuffer(orig) {...}
语法(如果不正确,对不起)? Thank you in advance. 先感谢您。
Bottom line: I made a mistake. 底线:我错了。
As everyone stated, the syntax 大家都说过,语法
DataBuffer(const DataBuffer& orig) : BaseBuffer(orig) {...}
is correct, and the error was elsewhere in my code. 是正确的,并且错误在我的代码的其他地方。 In my case, I was trying to copy the object before it had been initialized. 就我而言,我试图在对象初始化之前复制它。 Sorry for wasting everyone's time. 很抱歉浪费大家的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.