剑指offer-0x01
赋值运算函数
对于定义一个赋值运算符函数时,需要注意一下几点:
函数的返回类型必须是一个引用,因为只有返回引用,才可以连续赋值
传入的参数声明为常量引用,可以提高代码效率,同时赋值运算函数内不会改变传入的实例状态
一定要记得释放实例自身已有的内存,否则程序容易出现内存泄露
注意传入的参数和当前的实例是不是同一个实例,如果是同一个,则不用进行赋值操作,直接返回即可
自己的代码 求鄙视
//main.h
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
class CMyString
{
public:
CMyString(char* pData = NULL);
CMyString(const CMyString & str);
char* getStr();
~CMyString();
CMyString& operator = (const CMyString &str);
private:
char* m_pdata;
};
#endif // MAIN_H_INCLUDED
//main.cpp
#include <iostream>
#include <cstring>
#include "main.h"//must use "" not <>
using namespace std;
CMyString& CMyString::operator = (const CMyString &str)
{
if (this == &str)
return *this;//if itself = itself then return directly
//in case delete itself when delete
delete []m_pdata;
m_pdata = NULL;
m_pdata = new char[strlen(str.m_pdata)+1];
strcpy(m_pdata,str.m_pdata);
return *this;//return a value
}
char* CMyString::getStr()
{
return m_pdata;
}
CMyString::CMyString(char* pData)
{
int length = strlen(pData);
m_pdata = new char[length+1];
strcpy(m_pdata,pData);
}
CMyString::~CMyString()
{
delete []m_pdata;
}
int main()
{
CMyString str("i love china!");
CMyString str1;
str1 = str;
cout<<str1.getStr()<<endl;
cout << "Hello world!" << endl;
return 0;
}
E:\CodeBlocks\operator\main.h|14|error: 'char* CMyString::m_pdata' is private|
别人的代码
#include<iostream>
#include<cstring>
using namespace std;
class CMyString
{
public:
CMyString(char *pData=NULL);
CMyString(CMyString &str);
CMyString& operator=(CMyString &str);
~CMyString(void);
void Print(){ cout << m_pData; }
private:
char* m_pData;
};
CMyString::CMyString(char *pData)
{
if (NULL == pData)
{
m_pData = NULL;
return;
}
else
{
unsigned int len = strlen(pData)+1;
m_pData = new char[len];
for (int i = 0; i < len; i++)
m_pData[i] = pData[i];
m_pData[len] = '\0';
}
}
CMyString::CMyString(CMyString &str)
{
unsigned int len = strlen(str.m_pData) + 1;
m_pData = new char[len];
for (int i = 0; i < len; i++)
m_pData[i] = str.m_pData[i];
m_pData[len] = '\0';
}
CMyString & CMyString::operator=(CMyString &str)
{
if (this == &str)
return *this;
else
{
unsigned int len = strlen(str.m_pData) + 1;
char *pTemp = new char[len];
for (int i = 0; i < len; i++)
pTemp[i] = str.m_pData[i];
pTemp[len] = '\0';
delete[]m_pData;//出错!!!不解
m_pData = pTemp;
}
return *this;
}
CMyString::~CMyString()
{
delete [] m_pData;
}
int main()
{
char c1[10] = "majunfu";
CMyString s1(c1);
CMyString s2 = s1;
s1 = s2;
s1.Print();
s2.Print();
return 0;
}
keep calm and carry on