剑指offer第一题赋值运算符函数

#define _CRT_SECURE_NO_WARNINGS
#include<cstring>
#include<cstdio>
#include<iostream>

class CMyString
{
public:
	CMyString(char* pData = nullptr);
	CMyString(const CMyString& str);
	~CMyString();

	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
	{
		printf("This is the start\n");
		int length = strlen(pData);
		m_pData = new char[length + 1];
		strcpy(m_pData, pData);
	}
}
CMyString::CMyString(const CMyString &str)
{
	printf("This is the hhhhhh\n");
	int length = strlen(str.m_pData);
	m_pData = new char[length + 1];
	strcpy(m_pData, str.m_pData);
}



CMyString::~CMyString()
{
	delete[] m_pData;
	printf("This is the end\n");
}

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 = (char*)"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 = (char*)"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 = (char*)"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;
}

输出:

Test1 begins:
This is the start
The expected result is: Hello world.
The actual result is: Hello world.
This is the end
This is the end
Test2 begins:
This is the start
The expected result is: Hello world.
The actual result is: Hello world.
This is the end
Test3 begins:
This is the start
The expected result is: Hello world.
The actual result is: Hello world.
The expected result is: Hello world.
The actual result is: Hello world.
This is the end
This is the end
This is the end

猜你喜欢

转载自blog.csdn.net/yangtuoi/article/details/119254505