2013-02-09 61 views
0
class A 
{ 
protected: 
    int a; 
public: 
    A(); 
    A(int); 
    virtual void print()=0; 
    virtual ~A(); 
}; 

class B: public A 
{ 
    int b; 
public: 
    B(); 
    B(int,int); //initialize attributes a and b 
    void print(); //print a and b 
}; 

class C: public A 
{ 
    float c; 
public: 
    C(); 
    C(float,int); //initialize attributes a and c 
    void print(); //print a and c 
}; 

class D 
{ 
    int size; //number of objects in v 
    A **v; /* an array(a vector) of A pointers that allows me to have both B and C type objects */ 
public: 
    D(); 
    D(int); 
    D(D&); 
    ~D(); 
    D operator=(const D&); 
    void PrintAll(); 
}; 

爲d的所有方法:C++:堆分配前使用的typeid

D::D() 
{ 
    v=NULL; 
} 
D::D(int x) 
{ 
    size=x; 
    v=new A*[x]; 
    for(int i=0;i<x;i++) 
    { 
     if(i%2==0) 
      v[i]=new B(4,7); 
     else 
      v[i]=new C(3,5); 
    } 
} 

D::D(D& other) 
{ 
    size=other.size; 
    v=new A*[size]; 
    for(int i=0;i<size;i++) 
    { 
     if(i%2==0) 
     { 
      v[i]=new B(); 
      *v[i]=other.v[i][0]; 
     } 
     else 
     { 
      v[i]=new C(); 
      *v[i]=other.v[i][0]; 
     } 
    } 
} 

D::~D() 
{ 
    if(v!=NULL) 
    { 
     for(int i=0;i<size;i++) 
     { 
      delete v[i]; 
     } 
     delete[] v; 
    } 
} 
D D::operator=(const D& other) 
{ 
    if(v!=NULL) 
    { 
     for(int i=0;i<size;i++) 
     { 
      delete v[i]; 
     } 
     delete[] v; 
    } 
    size=other.size; 
    v=new A*[size]; 
    for(int i=0;i<size;i++) 
    { 
     if(i%2==0) 
     { 
      v[i]=new B(); 
      *v[i]=other.v[i][0]; 
     } 
     else 
     { 
      v[i]=new C(); 
      *v[i]=other.v[i][0]; 
     } 
    } 
    return *this; 
} 
void D::PrintAll() 
{ 
    cout<<"Printall():"<<endl; 
    for(int i=0;i<size;i++) 
     v[i]->print(); 
} 

正如可以看到的,d類的構造使得B或C型的對象作爲是奇數或偶數。如果我知道這一點,那麼我知道該怎麼寫運營商=和D的拷貝構造函數但如果d類的構造函數將使B或C類的對象隨機,那我怎麼才能寫拷貝構造函數(和運營商=)爲D類?我的猜測是我必須用的typeid運營商來解決這個問題。

回答

1

定義純虛擬方法clone作爲接口的一部分A定義 - clone應返回對象的副本。 覆蓋在每個BC類實現它。 在D類的拷貝構造函數和賦值操作符的實現使用A的界面來創建所需的類實例,而不是顯式調用newv[i] = other.v[i]->clone();。不需要RTTI,正常的多態性就可以做到。

+0

謝謝!我會做的。 – Cristi 2013-02-09 13:18:12