标签:ext cte 运算 text 事先 == new 应聘 c++
如下为类型CMyString的声明,请为该类型添加赋值运算符函数。
class CMyString { public: CMyString(char* pData = nullptr); CMyString(const CMyString& str); ~CMyString(void); CMyString& operator = (const CMyString& str); void Print(); private: char* m_pData; };
考虑到上述问题,就能较好的解决问题;但是,如果使程序更加鲁棒,我们应该考虑异常安全性。有两种方法:
#include <cstdio> #include <cstring> class CMyString { public: CMyString(char* pData = nullptr); CMyString(const CMyString& str); CMyString& operator = (const CMyString& str); void Print(); ~CMyString(void); private: char* m_pData; }; CMyString::CMyString(char* pData) { if(pData == nullptr) { m_pData = new char[1]; m_pData[0] = ‘\0‘; } else { int len = strlen(pData); m_pData = new char[len + 1]; strcpy(m_pData,pData); } } CMyString::CMyString(const CMyString& str) { int len = strlen(str.m_pData); m_pData = new char[len + 1]; strcpy(m_pData,str.m_pData); } //CMyString& CMyString::operator = (const CMyString& str){ // if(this == &str) // return *this; // // delete[] m_pData; // m_pData = nullptr; // // m_pData = new char[strlen(str.m_pData) + 1]; // strcpy(m_pData,str.m_pData); // // return *this; // //} CMyString& CMyString::operator = (const CMyString& str) { if(this != &str) { CMyString strTmp(str); char* pTmp = strTmp.m_pData; strTmp.m_pData = m_pData; m_pData = pTmp; } return *this; } void CMyString::Print() { printf("%s", m_pData); } CMyString ::~CMyString() { delete[] m_pData; } //=================TEST================== void Test1() { printf("Test1 begins:\n"); char* text = "Hello world!"; CMyString str1(text); CMyString str2; str2 = str1; printf("The expected result is: %s.\n",text); printf("The actual result is: "); str2.Print(); printf(".\n"); } void Test2(){ printf("Test2 begins:\n"); char* text = "Hello world!"; CMyString str1(text); str1 = str1; printf("The expected result is: %s.\n",text); printf("The actual result is: "); str1.Print(); printf(".\n"); } void Test3(){ printf("Test3 begins:\n"); char* text = "Hello world!"; CMyString str1(text); CMyString str2,str3; str3 = str2 = str1; printf("The expected result is: %s.\n",text); printf("The actual result is "); str2.Print(); printf(".\n"); printf("The actual result is "); str3.Print(); printf(".\n"); } int main() { Test1(); Test2(); Test3(); return 0; }
标签:ext cte 运算 text 事先 == new 应聘 c++
原文地址:https://www.cnblogs.com/ovs98/p/9842892.html