用超类的实例覆盖子类的实例 [英] Overwriting an instance of a subclass with an instance of a superclass

查看:84
本文介绍了用超类的实例覆盖子类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出一些东西(在Ada,实际上)我想出了以下代码。为什么是合法的?

Trying to figure something out (in Ada, actually) I came up with the following code. Why is it legal?

class Superclass {
public:
    virtual void Announce() {
        printf("I am the superclass\n");
    }
};

class Subclass : public Superclass {
public:
    void Announce() {
        printf("I am the subclass\n");
    }
};

int main() {
    Superclass osuper;
    Subclass osub;

    Superclass* p = &osub;
    *p = osuper;
    osub.Announce();

    return 0;
}

main(),我创建子类的实例,然后使用超类的实例物理覆盖它。然后我成功地调用了覆盖(和这样损坏的)对象上的 Subclass 方法。

In main(), I create an instance of Subclass, then physically overwrite it with an instance of Superclass. I then successfully call a method of Subclass on the overwritten (and so corrupted) object.

直接分配 osub = osuper ,因为这没有意义,但通过一个指针,我似乎绕过了。上面的代码编译正常,没有警告,但是当我调用 osub.Announce() osub 不再包含有效的子类对象。

I can't directly assign osub = osuper, because that makes no sense, but by going via a pointer I seem to bypass that. The above code compiles fine with no warnings, but by the time I call osub.Announce() the memory inside osub no longer contains a valid Subclass object.

这不能是类型安全的(甚至,通常安全),但编译器似乎完全幸福。为什么?

This can't possibly be type safe (or even, like, ordinarily safe), but the compiler seems perfectly happy. Why?

推荐答案

对某个对象使用=运算符无效,并且不覆盖任何内容,将会被使用。
如果你想真正覆盖内存中的对象,请尝试memcpy(p,& osub,sizeof(Superclass))。现在将被覆盖:)

Using the = operator on an object is not invalid, and it doesn't overwrite anything, a default copy constructor will be used. If you want to really overwrite the object in memory, try memcpy(p, &osub, sizeof(Superclass)). Now THAT would be an overwrite :)

请参阅 http:// www .cplusplus.com / articles / y8hv0pDG /

这篇关于用超类的实例覆盖子类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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