实例化后是否可以更改C ++对象的类? [英] Is it possible to change a C++ object's class after instantiation?

查看:99
本文介绍了实例化后是否可以更改C ++对象的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆类,它们都从公共基类继承相同的属性。基类实现了一些在一般情况下工作的虚函数,而每个子类为各种特殊情况重新实现了这些虚函数。

I have a bunch of classes which all inherit the same attributes from a common base class. The base class implements some virtual functions that work in general cases, whilst each subclass re-implements those virtual functions for a variety of special cases.

情况就是这样:我希望这些子类对象的特殊性是可以消耗的。本质上,我想实现一个 spend()函数,该函数会导致对象丢失其子类标识并恢复为具有一般情况的基类实例在基类中实现的行为。

Here's the situation: I want the special-ness of these sub-classed objects to be expendable. Essentially, I would like to implement an expend() function which causes an object to lose its sub-class identity and revert to being a base-class instance with the general-case behaviours implemented in the base class.

我应该注意派生类不会引入任何其他变量,因此基类和派生类的大小应相同内存。

I should note that the derived classes don't introduce any additional variables, so both the base and derived classes should be the same size in memory.

我打开摧毁旧对象并创建一个新对象,只要我可以在同一个内存地址创建新对象,所以现有指针没有破坏。

I'm open to destroying the old object and creating a new one, as long as I can create the new object at the same memory address, so existing pointers aren't broken.

以下尝试不起作用,并产生一些看似意外的行为。我在这里缺少什么?

The following attempt doesn't work, and produces some seemingly unexpected behaviour. What am I missing here?

#include <iostream>

class Base {
public:
    virtual void whoami() { 
        std::cout << "I am Base\n"; 
    }
};

class Derived : public Base {
public:
    void whoami() {
        std::cout << "I am Derived\n";
    }
};

Base* object;

int main() {
    object = new Derived; //assign a new Derived class instance
    object->whoami(); //this prints "I am Derived"

    Base baseObject;
    *object = baseObject; //reassign existing object to a different type
    object->whoami(); //but it *STILL* prints "I am Derived" (!)

    return 0;
}


推荐答案

你可以付出代价打破良好做法并维护不安全的代码。其他答案将为你提供令人讨厌的技巧来实现这一目标。

You can at the cost of breaking good practices and maintaining unsafe code. Other answers will provide you with nasty tricks to achieve this.

我不喜欢只说你不应该这样做的答案,但我想建议那里是实现所寻求结果的更好方法。

I dont like answers that just says "you should not do that", but I would like to suggest there probably is a better way to achieve the result you seek for.

策略模式很好。

您还应该考虑面向数据的设计,因为在您的情况下,类层次结构看起来不是明智的选择。

You should also think about data oriented design, since a class hierarchy does not look like a wise choice in your case.

这篇关于实例化后是否可以更改C ++对象的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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