天天看点

【剑指Offer】赋值运算符函数

按照自己浅薄的理解,敲了如下代码
           
#include <iostream>

using namespace std;
           
class CMyString
{
private:
	char *m_pChar;
public:
	CMyString();//这样的仅是声明,没有定义,把 ; 变成 {} 就是定义了!
	CMyString(char *m_pChar = NULL);
	CMyString(const CMyString &other);
	~CMyString();
	CMyString& operator=(const CMyString &other);
};

CMyString& CMyString::operator=(const CMyString &other)
{
	//检查是否为自己
	if(&other == this)
		return *this;
	//删除旧内存
	delete m_pChar;
	m_pChar = NULL;
	//分配新内存的大小,并复制字符
	m_pChar = new char[strlen(other.m_pChar) + 1];
	strcpy(m_pChar,other.m_pChar);

	return *this;
};

int main()
{
	CMyString s1 = "Hello";
	CMyString s2 = s1;
	
}
           

程序报错

1>test_sizeof.obj : error LNK2019: 无法解析的外部符号 "public: __thiscall CMyString::~CMyString(void)" ([email protected]@[email protected]),该符号在函数 _main 中被引用1>test_sizeof.obj : error LNK2019: 无法解析的外部符号 "public: __thiscall CMyString::CMyString(class CMyString const &)" ([email protected]@[email protected]@@Z),该符号在函数 _main 中被引用1>test_sizeof.obj : error LNK2019: 无法解析的外部符号 "public: __thiscall CMyString::CMyString(char *)" ([email protected]@[email protected]@Z),该符号在函数 _main 中被引用1> D:\MyProgram\Exercise\exc10\Debug\sizeof.exe : fatal error LNK1120: 3 个无法解析的外部命令
           

原因

仅给出了函数声明,未写函数的定义,修改如下

class CMyString
{
private:
	char *m_pChar;
public:
	CMyString()
	{
		m_pChar = NULL;
	}
	CMyString(char *pChar)
	{
		this->m_pChar = new char[strlen(pChar) + 1];
		strcpy(this->m_pChar,pChar);
	}
	CMyString(const CMyString &other){}
	~CMyString()
	{
		delete m_pChar;
		m_pChar = NULL;
	}
	CMyString& operator=(const CMyString &other);
};

CMyString& CMyString::operator=(const CMyString &other)
{
	//检查是否为自己
	if(&other == this)
		return *this;
	//删除旧内存
	delete m_pChar;
	m_pChar = NULL;
	//分配新内存的大小,并复制字符
	m_pChar = new char[strlen(other.m_pChar) + 1];
	strcpy(m_pChar,other.m_pChar);

	return *this;
};

int main()
{
	CMyString s1("Hello"),s2;
	 s2 = s1;

	return 0;

}