把传入参数设为引用,就可以不调用拷贝构造函数,少了一次拷贝节省了内存,返回值是该类的引用,这样才能连续赋值。
引用,防止产生一次拷贝副本。
#include <iostream>
#include <string.h>
using namespace std;
class CMystring
{
public:
CMystring(const char* pData = NULL);
CMystring(const CMystring &str );
~CMystring();
CMystring &operator=(const CMystring &str);
void print();
private:
char *m_pdata;
};
CMystring::CMystring(const char* pdata) {
if (pdata==NULL)
{
m_pdata = new char[1];
m_pdata[0] = '\0';
}
else
{
m_pdata = new char[strlen(pdata) + 1];
strcpy(m_pdata, pdata);
}
}
CMystring::CMystring(const CMystring &str)
{
int lenth = strlen(str.m_pdata);
m_pdata = new char[lenth + 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 = NULL;
m_pdata = new char[strlen(str.m_pdata) + 1];
strcpy(m_pdata, str.m_pdata);
return *this;
/*
CMyString temp(str);
char *ptemp = temp.m_pdata;
temp.m_pdata=m_pdata;
m_pdata=ptemp;
*/
}
void CMystring::print() {
printf("%s", m_pdata);
}
void Test1() {
printf("Test1 begin:\n");
char* text = "hello world";
CMystring str1(text);
CMystring str2;
str2 = str1;
printf("The expected string is %s\n:", text);
// str1.print();
printf("The actually result is:");
str2.print();
printf("\n");
}
/************************************************************************/
/* 自己复制test */
/************************************************************************/
void Test2() {
printf("Test2 begin:\n");
char *text = "Hello World2";
CMystring str2(text);
printf("The expected string is: %s\n", text);
printf("The actually result is:");
str2 = str2;
str2.print();
printf("\n");
}
/* 连续复制 */
void Test3() {
printf("Test3 begin:\n");
char *text = "Hello World3";
CMystring str1(text);
CMystring str2,str3;
printf("The expected string is: %s\n", text);
printf("The actually result is:");
str3 = str2=str1;
str3.print();
printf("\n");
}
int main() {
Test1();
Test2();
Test3();
system("pause");
return 0;
}