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/

相关文章:

c++ - 拥有多态对象集合的首选 C++ 习惯用法是什么?

c++ - 指向成员变量的多态指针

git - 在 Git 中以只读目的 check out 早期标记的最简洁方法

javascript - jQuery 克隆一个元素并更改子元素的属性以保持它们的唯一性

asp.net - 在 ASP.NET 问题中使用 WPF DLL 程序集

c++ - "strtol"返回不同的值

c++ - 如何用汇编语言写模数(C++中的%)

java - 使用通用父类型输入参数强制执行动态多态调用

ios - 如何从其中包含许多 UITextview 的 UIView 复制和检索数据

c++ - 多线程客户端服务器