음 복사생성자를 공부하다가 이상한점이 있어서요..
클래스의 멤버 변수를 그냥 스택에 선언했더니, 복사 생성해도 서로 다른 값을 가지더라구요,
(예를들어서 CAT firksy와 CAT si(frisky) 를 선언하면 두 개체의 멤버변수 값은 서로 다르게
도 지정이 가능하더라구요.)
그런데 왜, 멤버변수를 new로 힙에 할당해서 복사생성하면, 두 멤버변수의 주소는 같아지는걸까요.
게다가 (주소가 같으니 당연히도!) 한쪽 개체에서 그 멤버변수의 값을 바꾸면,
다른 하나의 값도 같이 바뀌더라구요 흐음-.
원래 기본 복사생성자는 메모리는 같고 말 그대로 참조처럼 복사만 해오는지요?
이것을 해결하려면 자신의 복사생성자를 따로 만들어야 합니까?
아래는 소스 원문입니다.
// 복사생성자
#include <iostream.h>
typedef unsigned short int USHORT;
class CAT
{
public:
CAT();
~CAT();
USHORT GetAge() {return *m_pItsAge;}
void SetAge(USHORT age) {*m_pItsAge = age;}
USHORT* Show() {return m_pItsAge;}
private:
USHORT *m_pItsAge;
};
CAT::CAT()
{
m_pItsAge = new USHORT(1);
}
CAT::~CAT()
{
}
int main()
{
int dump;
CAT frisky;
cout << "frisky's age is " << frisky.GetAge() << endl;
frisky.SetAge(2);
cout << "friksy's age is " << frisky.GetAge() << endl;
CAT si(frisky);
cout << "si- 's age is " << si.GetAge() << endl;
si.SetAge(3);
cout << "next year, si- 's age is " << si.GetAge() << endl;
cout << "and, frisky's age is " << frisky.GetAge() << " too." << endl;
cout << "frisky : " << frisky.Show() << " and, si- : " << si.Show() << endl;
cin >> dump;
return 0;
}
[출력]
frisky's age is 1
frisky's age is 2
si- 's age is 2
next year, si- 's age is 3
and, frisky's age is 3 too.
frisky : 0x003710e0 and, si- : 0x003710e0