Code
#include <iostream>
using namespace std;
class String
{
public:
String()
{
cout << "String() 생성자 호출" << endl;
strData = NULL;
len = 0;
}
String(const char *str)
{
cout << "String(const char *) 생성자 호출" << endl;
len = strlen(str);
strData = new char[len + 1];
cout << "StrData 할당: " << (void *)strData << endl;
strcpy(strData, str);
}
//매게변수로 String 클래스 타입을 받는것.
String(const String &ref)
{
cout << "String(String &ref) 생성자 호출" << endl;
strData = new char[ref.len + 1];
cout << "strData 할당: " << (void *)strData << endl;
strcpy(strData, ref.strData);
len = ref.len;
}
~String()
{
cout << "~String() 소멸자 호출" << endl;
delete[] strData;
cout << "strData 해제됨: " << (void *)strData << endl;
strData = NULL;
}
String &operator=(const String &rhs)
{
delete[] strData;
strData = new char[rhs.len + 1];
cout << "strData 할당: " << (void *)strData << endl;
strcpy(strData, rhs.strData);
len = rhs.len;
return *this;
}
char *GetstrData() const
{
return strData;
}
int Getlen() const
{
return len;
}
private:
char *strData;
int len;
};
int main()
{
String s1("안녕");
String s2(s1); //복사생성자
String s3;
s3.operator=(s1);
cout << s1.GetstrData() << endl;
cout << s2.GetstrData() << endl;
cout << s3.GetstrData() << endl;
}
Ex)