2013-02-09 18 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