2006-11-17 00:37:39
Effective C++ 3판
항목 12: 객체의 모든 부분을 빠짐없이 복사하자.
 
복사하려는 객체가 상속받은 sub class인 경우 복사 함수 안에서
부모에 복사 함수도 호출해서 부모에 멤버 역시 모두 복사 되도록  하자.
 
즉 자신에 클래스에 해당하는 멤버만 복사하면 부모에 멤버는 복사 되지 않음으로
임으로 꼭 호출해줘야 한다.
 
 
// copy operator code snippet
 
class CCustomer
{
public:
  CCustomer(void);
  CCustomer( const CCustomer& rhs ) ;
  virtual ~CCustomer(void);
 
public: 
  CCustomer& operator=(const CCustomer& rhs) ;
... 
private:
  string name ; 
  CDate lastTransaction ;
};
 
class CCPriorityCustomer :  public CCustomer
{
public:
  CCPriorityCustomer(int priority = 10);
  CCPriorityCustomer(const CCPriorityCustomer& rhs) ;
  virtual ~CCPriorityCustomer(void);
 
public:
  CCPriorityCustomer& operator=( const CCPriorityCustomer& rhs) ;
  ... 
private:
  int priority ; 
};
 
CCPriorityCustomer& CCPriorityCustomer::operator =( const CCPriorityCustomer& rhs )
{
  // 부모에 대입 연산자를 꼭 호출하자
 
CCustomer::operator=( rhs ) ;
  priority = rhs.priority ;
  return *this ;
}
 
 
 
잘못된 결과
==========================================================
name = 은짱~
last Transaction =
priority = 1
==========================================================
name = 은짱~
last Transaction =
priority = 2
 
 
부모까지 모두 복사된 경우
==========================================================
name = 은짱~
last Transaction =
priority = 1
==========================================================
name = 만세~
last Transaction =
priority = 2

EOF

+ Recent posts