将基类数据从一个派生类复制到另一个 [英] copy base class data from one derived class to another

查看:139
本文介绍了将基类数据从一个派生类复制到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个类:

typedef struct base
{
    float A;
    float B;
    ...
    base() : A(1.0f), B(1.0f) {}
} base;

class derived1 : base
{
    int C;
    int D;
};

class derived2 : base
{
    int E;
    int F;
};

我想将基类数据从一个派生类对象复制到另一个。

执行以下操作是否安全,仅将A,B等的基类值从一个对象复制到另一个对象?

And I would like to copy base class data from one derived class object to another.
Is it safe to do the following, to only copy the base class values of A, B, etc... from one object to another?

derived1* object1 = new derived1;
derived2* object2 = new derived2;

void make_object1()
{
    object1->C = 2;
    object1->D = 3;
}

void make_object2()
}
    object2->A = 4;
    object2->B = 5;
    object2->E = 6;
    object2->F = 7;
}

void transfer_base()
{
    *((base*)object1) = *((base*)object2);
}

假设我的程序经常需要执行此类操作,更好(更快的代码)的方式来做到这一点?
之所以这样做,是因为我编写了一个模拟和图形渲染器。我想仅通过从模拟对象中选择数据来尽可能高效地更新图形显示对象。模拟非常耗费CPU资源...
到目前为止,这种方法似乎有效,但是我担心可能有些东西被我忽略了...

Assuming my program would need to do this sort of operation often would there be a better (faster code) way to accomplish this? The reason that I'd doing this is I have written a simulation and a graphical renderer. I want to update graphical display objects with only select data from objects in the simulation as efficiently as possible. The simulation is extremely CPU intensive... So far this approach seems to be working however I'm concerned there may be something I'm overlooking...

推荐答案

代码

*((base*)object1) = *((base*)object2);

非常不安全,因为C样式强制转换几乎可以执行任何操作。

is quite unsafe, because the C style casts can do just about anything. Such as reinterpretation, or casting away constness.

相反,如果您要调用 base :: operator = ,然后明确调用

Instead, if you want to invoke base::operator=, then invoke that explicitly. Excplicit = good, implicit = bad.

即,

object1->base::operator=( *object2 );

这仍然不是安全的,因为切片可能会破坏派生类的类不变性。任何试图了解此代码中发生的情况的人都可能会对基类子对象中的值的突然更改感到惊讶,并浪费大量时间来尝试确定这些值的来源。但是至少它没有C样式转换那么糟糕。

This is still not “safe”, because the slicing may break the class invariant of the derived class. And anyone trying to get a handle on what happens in this code may be surprised by the sudden change of values in the base class sub-objects, and waste a lot of time trying to ascertain where those values are coming from. But at least it’s not as bad as the C style casting.

这篇关于将基类数据从一个派生类复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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