天天看點

【劍指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;

}