天天看點

【C++項目實戰】指派操作符重載

1 知識點

  • 建構類
  • 傳遞字元數組
  • 使用cstring中的函數strlen和strcpy
  • 指派操作符重載

2 代碼

#include <iostream>
#include <cstring>
using namespace std;
class CMyString{
public:
    CMyString(char* pData = nullptr): m_pData(pData){} // 構造函數,清單初始化
    CMyString(const CMyString& str): m_pData(str.m_pData){}// 重載構造函數,清單初始化
    CMyString& operator=(const CMyString &str);// 指派操作符重載聲明
    void getData(){ // 字元數組列印内容
        for(int i=0; *(m_pData+i) != 0; ++i){
            cout << *(m_pData+i);
        }
        cout << endl;
    }
    ~CMyString(){};
private:
    char* m_pData;
};

inline CMyString& CMyString::operator=(const CMyString &str){ // 使用引用傳回量
    if (this == &str){ // 判斷是否自身,如果是則直接傳回*this
        return *this;
    }
    m_pData = new char[strlen(str.m_pData)+1]; // 根據右值建立空間
    strcpy(m_pData, str.m_pData); // 拷貝
    return *this;
}

int main(){
    CMyString s1 = (char*)"Hello";
    CMyString s2 = (char*)"World";
    s2 = s1; 
    s2.getData();
    return 0;
}
           

3 輸出

Hello