c++ - 使用指针基类的 =operator 的多态性

标签 c++ polymorphism clone copy-constructor assignment-operator

事情是这样的,我想我需要就我正在使用的模式走另一条路,但我想我会先征求一些专家的意见。

我有一个维护基类指针动态列表的类 (UsingClass)。当向列表中添加一个新对象时,我必须弄清楚它是什么类型的对象,因为我不能真正让它以多态方式工作。下面的行标记为“这不会像我想要的那样工作!!”理想情况下会多态地使用感兴趣的 Derived 类中的 =operator,但不幸的是它只使用默认的 =operator 用于 Base 类......如果我将 Base 设为纯虚拟(基本上将其用于没有接口(interface)的接口(interface))它自己的数据成员),但我真的不想让派生类包含两者之间共有的成员(也许我需要切入诱饵并做到这一点)。

我认为我可能完全使用了错误的模式,但我不知道我应该考虑哪些替代方案。

我知道代码不一定能编译,但请和我一起工作。提前致谢!

    //code block
class Base { 
  protected: 
    int x;   
    float y;  
    string type;   // default to Derived1 or Dervied2 depending on the object inst  

  public:
    virtual int functionM(int l) = 0; 
    int functionN(int P);  
};  

class Derived1 : public Base { 
  protected:  
    int a;  

  public:  
   int functionM(int l); 
   float functionR(int h);  
};  

class Derived2 : public Base {  
  protected: 
     int b;  
     float r;  

  public: 
    int functionM(int l); 
    float functionR(int h); 
}; 

#define MAX_ARRAYSIZE   10 

class UsingClass { 
  private: 
    Base* myDerived1And2DynamicList[MAX_ARRAYSIZE];
    int indexForDynamicList;   

  public: 
    void functionAddDerivedToList(*Base myInputPtr) {  
       if((indexForDyanmicList + 1) < MAX_ARRAYSIZE) {  
           if(myInputPtr->type == "Derived1") {  
                myDerived1And2DynamicList[indexForDyanmicList+1] = new Derived1;  
                *myDerived1And2DynamicList[indexForDyanmicList+1] = *myInputPtr; // THIS WILL NOT WORK LIKE I WANT IT TO!!  
            } else if (myInputPtr->type == "Derived2") { 
                myDerived1And2DynamicList[indexForDyanmicList+1] = new Derived2;  
                *myDerived1And2DynamicList[indexForDyanmicList+1] = *myInputPtr; // THIS WILL NOT WORK LIKE I WANT IT TO!!  
            } 
        }  
     } // end of void function 
};

最佳答案

无需检查类型,您可以简单地向“Base”类添加一个虚函数并调用它。这会将 void functionAddDerivedToList(*Base myInputPtr) 简化为以下内容:

void functionAddDerivedToList(*Base myInputPtr)
{
   if((indexForDyanmicList + 1) < MAX_ARRAYSIZE) {  
       myDerived1And2DynamicList[indexForDyanmicList+1] = myInputPtr->clone();
   }
}

Clone 将始终被实现以调用类的复制构造函数。所以在 Base 中,添加以下内容:

virtual Base* clone() = 0;

实现总是采用这种形式(示例是 Derived1,在您的示例中是 Base 的子类):

virtual Base* clone() { return new Derived1(*this); }

关于c++ - 使用指针基类的 =operator 的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6785472/

相关文章:

java - 在 Java 中复制 HashMap

c++ - 如果我有角度和轴,如何在 PCL 中进行旋转平移?

java - Android JNI - 从 C++ 调用 Android UI 线程上的函数

c++ - 添加具有模板特化的方法

c# - 不能在 C# 中的同一方法上使用虚拟和重写

git svn 获取 'Error running context: Software caused connection abort at...'

c++ - 为什么从属性页调用 afxmessagebox 到扩展 dll 时 mfc 死锁

java - 为什么 instanceof 在这种情况下返回成功

c++ - C++虚函数的输出

javascript - jquery 克隆元素在变量中被改变