如何动态分配内存到多态数据类型? [英] How do I dynamically allocate memory to a polymorphic data type?

查看:180
本文介绍了如何动态分配内存到多态数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合类,可以多态地保存和管理任何类型的Multinumber。这可以是类型为Pair,Rational或Complex的对象。我遇到的问题是,这个类需要动态内存管理,在许多情况下,如下面的功能,我不知道要分配什么类型。因为集合是类型不可知的,我不知道我应该做Multinumber * var = new Complex,Rational或Pair。有什么方法来检查我首先添加的类型,或将此信息存储在另一种数据类型,而不会产生切片效应?我有这个问题的一个函数是:

I have a set class that can polymorphically hold and manage anything of type Multinumber. This can be an object of type Pair, Rational, or Complex. The problem that I am running into is that this class requires dynamic memory management and in many cases, such as the function below, I don't know what type to allocate. Since the set is type agnostic, I can't know if I am supposed to do Multinumber* var=new Complex, Rational, or Pair. Is there any way to check the type of what I am adding first, or to store this information in another data type without the slicing effect? One function where I have this problem is this:

bool Set::addElement(Multinumber* newElement)
{
    bool success = false;
    if(isFull())
    {
        resize();
    }
    if(!isMember(newElement))
    {
        setArray[numElements] = newElement;
        numElements++;
        success = true;
    }
    return success;
}

编辑:我说的是这种情况, / em>我可能分配的地方,例如当一个操作符+被调用并且必须立即在这里发送对象,并且调用类不知道什么是类型。

I am talking about situations where this is the only place that I could possibly allocate, such as when an operator+ is called and must immediately send the object here, and the calling class does not know what the type is. It happens in my code in the Set operator+ overload, since I the Set doesn't know what it is storing.

推荐答案

我在Set运算符+重载的代码中发生了这种情况。不明白为什么你会在这里分配。但除此之外,请使用虚拟副本成语。

I don't see why you would be allocating here. But aside from that, use the virtual clone idiom.

这篇关于如何动态分配内存到多态数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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