C++转换为派生和父结构

Meg*_*ron 2 c++ casting

我想知道如何用C++做点什么.我希望能够创建此结构的实例

struct ComplexInstruction : simple_instr
{
    bool isHead;
    bool isTail;
};
Run Code Online (Sandbox Code Playgroud)

它复制simple_instr实例中的所有数据.基本上,我想做这样的事情

ComplexInstruction cInstr = instr; // <- instance of simple_instr
Run Code Online (Sandbox Code Playgroud)

并且让cInstr拥有instr中所有数据的副本,而不必复制每个字段(因为它们有很多).我不知道这是怎么做的,我不认为简单的铸造会起作用.另外,可以反过来吗?即具有ComplexInstruction的实例,并将其转换为simple_instr的实例.我认为这可以通过演员来完成,但我没有很多c ++的经验

提前致谢

San*_*nto 8

在派生类中创建一个构造函数以从基类初始化.

class Base
{
  int x;
public:
  Base(int a) : x(a){}
};

class Derived : public Base
{
public:
  Derived(const Base & B) : Base(B){}
};
Run Code Online (Sandbox Code Playgroud)

请注意,如果您有一个Base的派生对象,您实际上有一个基础对象,您可以安全地使用基本副本ctor.

Derived d;
Base b(d);//the parts of Base that are in Derived are now copied from d to b.
          //Rest is ignored.  
Run Code Online (Sandbox Code Playgroud)

如果你想要更详细,你可以在派生类中编写一个operator =

void operator=(const Base & b)
{
  Base::operator=(b);
  //don't forget to initialize the rest of the derived members after this, though.
}
Run Code Online (Sandbox Code Playgroud)

这一切都取决于你想做什么,真的.重要的是:明确.不要留下未经初步的班级成员.