- /*
- 题目:如下为类型CMyString的声明,请为该类型添加赋值运算符函数。
- */
- #include <cstdio>
- #include <cstring>
- using namespace std;
- class CMyString {
- public :
- CMyString(char * pData = NULL);
- CMyString(const CMyString & str);
- ~CMyString(void);
- CMyString & operator = (const CMyString & str);
- void print();
- private :
- char * m_pData;
- };
- CMyString::CMyString(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);
- }
- }
- CMyString::CMyString(const CMyString & str) {
- m_pData = new char[strlen(str.m_pData) + 1];
- strcpy(m_pData, str.m_pData);
- }
- CMyString::~CMyString() {
- delete [] m_pData;
- }
- /*
- // 解法1:经典解法,未考虑内存不足导致new char抛出异常
- CMyString & CMyString::operator = (const CMyString & str) {
- if(this == &str) {
- return *this;
- }
- delete [] m_pData;
- m_pData = NULL;
- m_pData = new char[strlen(str.m_pData) + 1];
- strcpy(m_pData, str.m_pData);
- return * this;
- }
- */
- // 解法2:考虑异常安全性,分配内容成功后再释放原来的内容
- CMyString & CMyString::operator = (const CMyString & str) {
- if(this == &str) {
- return *this;
- }
- char * pTemp = new char[strlen(str.m_pData) + 1];
- delete [] m_pData;
- m_pData = NULL;
- m_pData = pTemp;
- strcpy(m_pData, str.m_pData);
- return *this;
- }
- /*
- // 解法3:先创建一个临时实例,再交换临时实例和原来的实例
- CMyString & CMyString::operator = (const CMyString & str) {
- if(this != &str) {
- CMyString strTemp(str);
- // 需要交换,因为对象的两个实例空间上不能有交集
- char * pTemp = strTemp.m_pData;
- strTemp.m_pData = m_pData;
- m_pData = pTemp;
- }
- return * this;
- }
- */
- void CMyString::print() {
- printf("%s\\n", m_pData);
- }
- void test1() {
- // 普通赋值
- printf("test1\\n");
- CMyString str1("hello, world.");
- CMyString str2;
- str2 = str1;
- str1.print(); // hello, world.
- str2.print(); // hello, world.
- }
- void test2() {
- // 连续赋值
- printf("test2\\n");
- CMyString str1("hello, world.");
- CMyString str2, str3;
- str3 = str2 = str1;
- str3.print(); // hello, world.
- }
- void test3() {
- // 赋值给自己
- printf("test3\\n");
- CMyString str("hello, world.");
- str = str;
- str.print(); // hello, world.
- }
- int main(void) {
- test1();
- test2();
- test3();
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/2004201512332.html
来源: http://www.codesnippet.cn/detail/2004201512332.html