复制构造函数和基类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 $ c>
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