編寫String類的普通建構函式、拷貝建構函式、解構函式、賦值函式
題目:編寫類String的建構函式、解構函式和賦值函式,已知類String的原型為:
class String
{
public:
String(const char *str = NULL); // 普通建構函式
String(const String &other); // 拷貝建構函式
~String(void); // 解構函式
String &operate = (const String &other); // 賦值函式
private:
char *m_data; // 用於儲存字串
};
解答:
(1)//普通建構函式
建構函式:建構函式是一種特殊的方法,主要用來在建立物件時初始化物件,即為物件成員變數賦初始值,總與new運算子一起使用在建立物件的語句中,特別的一個類可以有多個建構函式,可根據其引數個數的不同或引數型別的不同來區分它們,即建構函式的過載。
String::String(const char *str)
{
if(str == NULL)
{
m_data = newchar[1];
*m_data ='\0';
}
else
{
int length = strlen(str);
m_data = newchar[length+1];
strcpy(m_data,str);
}
}
(2)//拷貝建構函式
拷貝建構函式:拷貝建構函式,是一種特殊的建構函式,它由編譯器呼叫來完成一些基於同一類的其他物件的構建及初始化。其唯一的引數(物件的引用)是不可變的(const型別)。此函式經常用在函式呼叫時使用者定義型別的值傳遞及返回。拷貝建構函式要呼叫基類的拷貝建構函式和成員函式。如果可以的話,它將用常量方式呼叫,另外,也可以用非常量方式呼叫。
String::String(const String &other)
{
int length = strlen(other.m_data);
m_data = newchar[length+1];
strcpy(m_data,other.m_data);
}
(3)// String的解構函式
解構函式:解構函式(destructor) 與建構函式相反,當物件脫離其作用於時(例如物件所在的函式已呼叫完畢),系統自動執行解構函式。解構函式往往用來做“清理善後” 的工作(例如在建立物件時用new開闢了一片記憶體空間,應在退出前在解構函式中用delete釋放)。
String::~String(void)
{
delete []m_data; // 或deletem_data;
}
(4)//賦值函式
String & String::operate =(const String&other) // 輸入引數為const型
{
if(this == &other) //檢查自賦值
return *this;
delete []m_data; //釋放原有的記憶體資源
int length = strlen( other.m_data );
m_data = newchar[length+1]; //對m_data加NULL 判斷
strcpy(m_data, other.m_data );
return *this; //返回本物件的引用
}
注意:在這個類中包括了指標類成員變數m_data,當類中包括指標類成員變數時,一定要過載其拷貝建構函式、賦值函式和解構函式。