#include<iostream>
using namespace std;
class String
{
public:
String(char * pData = NULL);
String(const String& str);
~String();
String& operator=(const String& str);
void print();
private:
char * m_pData;
};
String::String(char * pData)
{
if (pData == NULL)
{
m_pData = new char[1];
m_pData[0] = '\0';
}
else
{
int length = strlen(pData);
m_pData = new char[length + 1];
strcpy(m_pData, pData);
}
}
String::String(const String& str)
{
int length = strlen(str.m_pData);
m_pData = new char[length + 1];
strcpy(m_pData, str.m_pData);
}
String::~String()
{
delete[] m_pData;
}
/*
//常规方法
String& String::operator=(const String& str)
{
if (this == &str)
return *this;
delete[] m_pData;
m_pData = NULL;
m_pData = new char[strlen(str.m_pData) + 1];
strcpy(m_pData, str.m_pData);
return *this;
}
*/
/*
//先分配,再释放
String& String::operator=(const String& str)
{
if (this == &str)
return *this;
char * temp = new char[strlen(str.m_pData) + 1];;
delete[] m_pData;
m_pData = temp;
strcpy(m_pData, str.m_pData);
return *this;
}
*/
//创建临时变量
String& String::operator=(const String& str)
{
if (this == &str)
return *this;
String ss(str);
char * temp = ss.m_pData;
ss.m_pData = m_pData;
m_pData = temp;
return *this;
}
//测试代码
void String::print()
{
cout << m_pData << endl;
}
void Test1()
{
cout << "Test1 begins:\n";
char * text = "hello world";
String str1(text);
String str2;
str2 = str1;
cout << "The expected result is: " << text << endl;
cout << "The actual result is:";
str2.print();
cout << endl;
}
//赋值给自己
void Test2()
{
cout << "Test1 begins:\n";
char * text = "hello world";
String str1(text);
str1 = str1;
cout << "The expected result is: " << text << endl;
cout << "The actual result is:";
str1.print();
cout << endl;
}
//连续赋值
void Test3()
{
cout << "Test1 begins:\n";
char * text = "hello world";
String str1(text);
String str2, str3;
str3 = str2 = str1;
cout << "The expected result is: " << text << endl;
cout << "The actual result is:";
str2.print();
cout << endl;
cout << "The expected result is: " << text << endl;
cout << "The actual result is:";
str3.print();
cout << endl;
}
int main()
{
Test1();
Test2();
Test3();
return 0;
}
剑指offer——赋值运算符函数
最新推荐文章于 2021-09-08 23:17:37 发布