c++中有關String類的構造函數等

String類定義如下:

class String
{
public:
	String(const char* str = NULL);
	String(const String &other);
	~ String(void);
	String & operator =(const String &other);
private:
	char *m_data;
};

各個函數的實現如下:

//constructor
String::String(const char* str)
{
	if(str == NULL)
	{
		m_data = new char[1];//這裏用new[]是爲了在析構裏統一使用delete[]
		*m_data = '\0';
	}
	else
	{
		m_data = new char[strlen(str)+1];
		strcpy(m_data,str);
	}
}

//copy constructor
String::String(const String &other)
{
	m_data = new char[strlen(other.m_data)+1];
	if(m_data == NULL)
	{
		cerr<<"allocator memory failed in String::String(const String &other)"<<endl;
	}
	else
	{
		strcpy(m_data,other.m_data);
	}
}

//destructor
String::~String(void)
{
	delete [] m_data;
}

//operator
String& String::operator =(const String &other)
{
	if(this == &other)
	{
		return *this;
	}
	delete [] m_data;
	m_data = new char[strlen(other.m_data)+1];
	strcpy(m_data,other.m_data);
	return *this;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章