复制构造函数和基类C ++ [英] copy constructors and base classes C++

查看:157
本文介绍了复制构造函数和基类C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够从基类初始化一个派生类,例如:

I'd like to be able to initialize a derived class from a base class, like so:

class X {
   public:
   X() : m(3) {}
   int m;
};

class Y : public X {
   public: 
   Y() {}
   Y(const & X a)  : X(a) {}
};

有什么危险或不寻常的做法吗?我想要它,因为我反序列化一堆对象类型我不立即知道,所以我基本上想使用X作为一些临时存储,而我正在读整个序列化文件,然后创建我的Y对象和W,X,Yobjs,取决于数据)。

Is there anything dangerous or unusual by doing that? I want it because I'm deserializing a bunch of objects who's type I don't immediately know, so I basically want to use X just as some temp storage while I'm reading the whole serialized file, and then create my Y objects (and W, X, Y objs, depending on the data) using that data afterwards. Maybe there's a easier way I'm missing.

谢谢!

推荐答案

p>只要X有正确的拷贝ctor(自动生成或不生成),并设置 Y (如果有)的其他成员,

There should be no problem with this as long as X has a correct copy ctor (auto-generated or not) and you set the other members of Y (if any) to appropriate defaults.

我假设 Y 会有一些setter方法来更新 Y

I assume that Y would have some setter methods to update Y with the results of subsequent information from the serialization stream?

另请注意,您的 Y X 构造函数应该有一个看起来更像的签名:

Also note that your Y from an X constructor should have a signature that looks more like:

Y( X const & a)   // the X was in an invalid place before

这篇关于复制构造函数和基类C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆