如何将基类对象分配给派生类对象? [英] how to assign base class object to a derived class object?

查看:71
本文介绍了如何将基类对象分配给派生类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个基类A和一个公共派生的类B,我应该如何将A对象分配给B的A基类子对象?

Assuming I have a base class A and publicly derived class B, how should I assign A object to the A base class subobject of B?

class A {...};
class B : public A {...};
A a(..);
B b(..);
static_cast<A&>(b) = a; ???

在不为B编写赋值运算符的情况下可行吗?将b强制转换为A&会存在任何潜在问题吗?那符合标准吗?

Is that doable without writing assignement operator for B? Are there any potential problems with casting b to A&? Is that standard conformant?

推荐答案

写另一个答案来演示为什么以及如何将基类对象分配给派生类对象.

Writing another answer to demonstrate why and how assign a base class object to a derived class object.

struct TimeMachineThing_Data {
..
..
};

class TimeMachineThing : private TimeMachineThing_Data
{
    static std::stack<TimeMachineThing_Data> m_stateHistory;

    void SaveState() {
        m_stateHistory.push_back( static_cast<TimeMachineThing_Data&>(*this) );
    }

    void RestoreState() {
        static_cast<TimeMachineThing_Data&>(*this) = m_stateHistory.front();
        m_stateHistory.pop_front();
    }
};

这非常有用且完全合法.

It's very useful and fully legitimate.

(这里是私有继承,所以仅在内部使用TimeMachineThing IS-A TimeMachinetime_Data)

(Here is private inheritance, so only internally TimeMachineThing IS-A TimeMachinetime_Data)

另一个.

struct StructWithHundresField {
  string title;
  string author;
  ...

  StructWithHundresField() {
    ...
  }
};

class EasyResetClass : public StructWithHundresField {
  int not_reset_this_attriute;
public:
  void ResetToInitialStateAtAnyTime() {
    static_cast<StructWithHundresField&>(*this) = StructWithHundresField();
  }
}

这篇关于如何将基类对象分配给派生类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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