劍指Offer--面試題1:賦值運算子函式

湯姆魚發表於2019-12-29
SCDN部落格:https://blog.csdn.net/weixin_41923658 
知乎:https://www.zhihu.com/people/Mister-Yu2019/activities  
簡書:https://www.jianshu.com/u/d17d68ac2c8c 
微信公眾號:「湯姆魚」 

                          劍指Offer--面試題1:賦值運算子函式

-------------------------------------手動分割線-------------------------------------------

題目:如下為型別CMyString的宣告,請為該型別新增賦值運算子函式。

程式碼如下:

#include<cstring>
#include<cstdio>
 
class CMyString
{
public:
	CMyString(char* pData = nullptr);
	CMyString(const CMyString& str);
	~CMyString(void);
 
	CMyString& operator = (const CMyString& str);
 
	void Print();
 
private:
	char* m_pData;
};
 
CMyString::CMyString(char *pData)
{
	if (pData == nullptr)
	{
		m_pData = new char[1];
		m_pData[0] = '\0';
	}
	else
	{
		int length = strlen(pData);
		m_pData = new char[length + 1];
		strcpy(m_pData, pData);
	}
}
 
CMyString::CMyString(const CMyString &str)
{
	int length = strlen(str.m_pData);
	m_pData = new char[length + 1];
	strcpy(m_pData, str.m_pData);
}
 
CMyString::~CMyString()
{
	delete[] m_pData;
}
 
CMyString& CMyString::operator = (const CMyString& str)
{
	if (this == &str)
		return *this;
 
	delete[]m_pData;
	m_pData = nullptr;
 
	m_pData = new char[strlen(str.m_pData) + 1];
	strcpy(m_pData, str.m_pData);
 
	return *this;
}
 
// ====================測試程式碼====================
void CMyString::Print()
{
	printf("%s", m_pData);
}
 
void Test1()
{
	printf("Test1 begins:\n");
 
	char* text = "Hello world";
 
	CMyString str1(text);
	CMyString str2;
	str2 = str1;
 
	printf("The expected result is: %s.\n", text);
 
	printf("The actual result is: ");
	str2.Print();
	printf(".\n");
}
 
// 賦值給自己
void Test2()
{
	printf("Test2 begins:\n");
 
	char* text = "Hello world";
 
	CMyString str1(text);
	str1 = str1;
 
	printf("The expected result is: %s.\n", text);
 
	printf("The actual result is: ");
	str1.Print();
	printf(".\n");
}
 
// 連續賦值
void Test3()
{
	printf("Test3 begins:\n");
 
	char* text = "Hello world";
 
	CMyString str1(text);
	CMyString str2, str3;
	str3 = str2 = str1;
 
	printf("The expected result is: %s.\n", text);
 
	printf("The actual result is: ");
	str2.Print();
	printf(".\n");
 
	printf("The expected result is: %s.\n", text);
 
	printf("The actual result is: ");
	str3.Print();
	printf(".\n");
}
 
int main(int argc, char* argv[])
{
	Test1();
	Test2();
	Test3();
 
	return 0;
}
 複製程式碼


相關文章