2012-12-19 4 views
8

나는 기본 클래스와 파생 클래스 두 개를 가지고 있으며 파생 클래스의 개체에 대한 포인터를 예제와 같이 다른 클래스 중 하나로 복사해야합니다.두 파생 클래스의 C++ 복사본

class Base 
{ 
public: 
    Base(const Base& other); 
} 

class Derived1 :public Base 
{ 
public: 
    Derived1(const Derived& other): Base(other){...}; 
} 

class Derived2: public Base 
{ 
public: 
    Derived2(const Derived& other): Base(other){...}; 
} 

main() 
{ 
    Derived 1 d1; 
    Derived2 d2(d1) 
} 

나는 (허용 upcasting) 파생 1 TI베이스에서 통과하려고하고 * dynamic_cast는 * Derived2에 대한 자료 및 복사 생성자를 호출하지만 작동하지 않습니다. 2 개의 파생 된 오브젝트 사이에 두 오브젝트의 Base 부분 만 복사하면됩니다.

+0

Derived2 내의 Derived1에 대한 전체 정보에 액세스해야하거나 그 반대의 경우에도 클래스를 강력하게 연결해야합니다. 어쩌면 각 클래스의 포인터를 다른 클래스에 저장하는 것이 아니라 Derived1과 Derived2에 접근 자 함수를 구현하는 것이 더 쉽고, Derived1과 Derived2에 대한 참조를 저장하고 필요한 항목을 계산하는 OperateOnDerived 클래스도 있습니다. – tmaric

답변

5

기본 클래스 부분 만 복사하려는 경우 기본 클래스를받는 생성자를 만드십시오.

Derived2(const Base& other): Base(other){...}; 

Derived1(const Base& other): Base(other){...}; 
관련 문제