类中赋值运算符重载函数
生活随笔
收集整理的這篇文章主要介紹了
类中赋值运算符重载函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
聲明一個字符串類,為這個類型添加賦值運算符
class MyString { public://構造函數MyString(char* pData = NULL);//構造函數MyString(const MyString& str);//析構函數~MyString(void);//賦值運算符MyString& operator=(const MyString& str);private:char* m_pData; };該字符串類中只有兩個構造函數,一個析構,一個賦值運算符的重載,著重來說賦值運算符的重載,重載之前將構造函數和析構函數實現了
MyString::MyString(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);} }MyString::MyString(const MyString &str) {m_pData = new char[strlen(str.m_pData) + 1];strcpy(m_pData, str.m_pData); }MyString::~MyString() {delete[] m_pData; }S1 = S2 ,S1傳給第一個參數,S2傳給第二個參數,賦值自然順理成章,以下是代碼:
MyString& MyString::operator=(const MyString& str) {if (this != &str) //如果相等,即就是給自身賦值,直接返回*this;{delete[]m_pData; //釋放原實例中 m_pData的內存m_pData = NULL;m_pData = new char[strlen(str.m_pData) + 1];strcpy(m_pData, str.m_pData); //重新申請空間并完成拷貝}return *this; }但是,以上代碼書上說,還存在安全問題,說是,上例的賦值運算重載中釋放了原有的實例對象內存,而去重新申請了內存,但是,一旦申請內存失敗,也就是說new char 拋出了異常,m_pData將是一個空指針,問題就是一大堆,怎么辦呢?一種方法是:先new 一塊新內存,在delete釋放已有的內存,這樣,只有在內存分配成功之后才會釋放原有內容,分配失敗,原來的實例也不會被修改; MyString& MyString::operator=(const MyString& str) {if (this != &str){char* tmp = new char[strlen(str.m_pData) + 1];if (tmp != nullptr){delete[]m_pData;m_pData = NULL;m_pData = tmp;strcpy(m_pData, str.m_pData);}}return *this; }還有更好的寫法: MyString& MyString::operator=(const MyString& str) {if (this != &str){MyString tmp(str);swap(m_pData,tmp.m_pData); //庫中交換函數 swap();}return *this; }還有大神是這樣寫的; String& operator=(String rhs) // 傳值{swap(rhs);return *this;}
拙見,歡迎糾正;
good
轉載于:https://www.cnblogs.com/melons/p/5791860.html
總結
以上是生活随笔為你收集整理的类中赋值运算符重载函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GDB动态库搜索路径
- 下一篇: 1-4:学习shell之操作文件与目录