一個空類編譯器預設産生4個函數:
預設構造函數、析構函數、拷貝構造函數、指派函數。
這些函數都是public,且是内聯函數。
以string類為例,為不引起重命名改為Mystring(也可以使用别的命名空間)
class Mystring
{
public:
Mystring(const char *str = NULL); //普通構造函數
Mystring(const Mystring &other); //拷貝構造函數
~Mystring(); //析構函數
Mystring &operator=(const Mystring &other); //指派函數
private:
char *m_data;
};
/*實作*/
//普通構造函數
Mystring::Mystring(const char *str)
{
if (NULL == str) //當str為空時,指派為空字元串
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length + 1]; //配置設定資源
strcpy(m_data,str); //複制内容
}
}
//拷貝構造函數
Mystring::Mystring(const Mystring &other)
{
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data,other.m_data);
}
//析構函數
Mystring::~Mystring()
{
delete []m_data;
}
//指派函數
Mystring& Mystring::operator=(const Mystring &other)
{
if (this == &other) //是否是自我指派
{
return *this;
}
delete []m_data; //釋放原有資源
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data,other.m_data);
return *this; //傳回本對象引用
}
該四個函數在什麼時候調用?
class Mystring
{
public:
Mystring(const char *str = NULL) //普通構造函數
{
cout << "Mystring(const char *str) 普通構造函數" << endl;
}
Mystring(const Mystring &other) //拷貝構造函數
{
cout << "Mystring(const Mystring &other) 拷貝構造函數" << endl;
}
~Mystring() //析構函數
{
cout << "~Mystring()析構函數" << endl;
}
Mystring &operator=(const Mystring &other) //指派函數
{
cout << "Mystring& operator=(const Mystring &other) 指派函數" << endl;
return *this;
}
};
void main()
{
Mystring str1; //調用普通構造函數,此時str為空
Mystring str2("Hello Word");//調用普通構造函數
Mystring ste3 = "hello"; //調用普通構造函數
Mystring *str4 = new Mystring(); //調用普通構造函數
Mystring str5(str2); //調用拷貝構造函數
str1 = str2; //調用指派函數
delete str4;
}
顯示結果:
Mystring(constchar *str)普通構造函數
Mystring(constchar *str)普通構造函數
Mystring(constchar *str)普通構造函數
Mystring(constchar *str)普通構造函數
Mystring(constMystring &other)拷貝構造函數
Mystring&operator=(const Mystring &other) 指派函數
~Mystring()析構函數
~Mystring()析構函數
~Mystring()析構函數
~Mystring()析構函數
~Mystring()析構函數