通過user_string類,來看如何撰寫構造函數。
#include <string.h>
#include <stdio.h>
class user_string
{
public :
?user_string();
?user_string(const char *src);
?user_string(const user_string &other);
?user_string &operator = (const user_string &other);
?
?~user_string();
?void show();
private:
?char *m_pdata;
};
user_string::user_string()
{
}
user_string::user_string(const user_string &other)
{
}
user_string::user_string(const char*src)
{
?if ( src == NULL )
?{
??m_pdata = new char[1];
??m_pdata[0] = '\0';
?}
?else
??m_pdata = new char [strlen(src) + 1];
??strcpy(m_pdata, src);
}
user_string::~user_string()
{
?delete []m_pdata;
}
user_string & user_string::operator = (const user_string &other)
{
?if (?this == &other )
??return *this;
?
?delete []m_pdata;
?m_pdata = new char[strlen(other.m_pdata) + 1];
?strcpy(m_pdata, other.m_pdata);
?return * this;
}
void user_string::show()
{
?printf("%s", m_pdata);
}
void main()
{
?user_string a("123");
?user_string b("456");
?b = b;
?b = a;
?//b = a;
?
}
posted on 2006-06-03 12:06 AlanTop 閱讀(318) 評論(2) 編輯 收藏 引用 所屬分類: C++