剑指offer-面试题1:赋值运算符函数
来源:互联网 发布:淘宝详情页尺寸790? 编辑:程序博客网 时间:2024/05/02 01:21
对于定义一个赋值运算符函数时,需要注意一下几点:
(1)函数的返回类型必须是一个引用,因为只有返回引用,才可以连续赋值
(2)传入的参数声明为常量引用,可以提高代码效率,同时赋值运算函数内不会改变传入的实例状态
(3)一定要记得释放实例自身已有的内存,否则程序容易出现内存泄露
(4)注意传入的参数和当前的实例是不是同一个实例,如果是同一个,则不用进行赋值操作,直接返回即可。
经典解法:
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; }考虑异常安全性的解法及测试用例
#include <iostream>#include <string>#include <string.h>using namespace std;class CMyString{public:CMyString(const char* pData = NULL);CMyString(const CMyString& str);CMyString& operator =(const CMyString& str);~CMyString(void);void print(); private:char* m_pData;}; CMyString::CMyString(const char* pData){if(pData == NULL){m_pData = new char[1];strcpy(m_pData, "\0");}else{int length = strlen(pData);m_pData = new char[length+1];strcpy(m_pData, pData);}} CMyString::CMyString(const CMyString& str){int length = strlen(str.m_pData);m_pData = new char[length+1];strcpy(m_pData, str.m_pData);} CMyString::~CMyString(void){delete[] m_pData;} CMyString& CMyString::operator =(const CMyString& str){if(this != &str){CMyString strTemp(str); char* pData = strTemp.m_pData;strTemp.m_pData = m_pData;m_pData = pData;} return *this;}void CMyString::print(){cout << m_pData << endl;} //把一个CMyString的实例赋值给另外一个实例void test1(){cout << "test1:" << endl;const char* test = "hello world";CMyString str1(test);CMyString str2;str2 = str1; cout<<"The expected result is: "; str1.print(); cout<<"the actual result is: "; str2.print();}//把一个CMyString的实例赋值给它自己void test2(){cout << "test2:" << endl;const char* test = "hello world";CMyString str1(test);cout<<"The expected result is: "; str1.print();str1 = str1;cout<<"the actual result is: "; str1.print();}//连续赋值void test3(){cout << "test3:" << endl;const char* test = "hello world";CMyString str1(test);cout<<"The expected result is: "; str1.print();CMyString str2, str3;str3 = str2 = str1;cout<<"the actual result is: "; str2.print(); str3.print();} int main(){test1();test2();test3(); return 0;}
0 0
- 《剑指Offer》面试题1:赋值运算符函数
- 剑指offer:面试题1 赋值运算符函数
- 剑指offer-面试题1:赋值运算符函数
- 剑指offer面试题1之赋值运算符函数
- 剑指offer-面试题1:赋值运算符函数
- 剑指offer 面试题1 赋值运算符函数
- 【剑指offer】面试题1:赋值运算符函数
- 剑指offer面试题1:赋值运算符函数
- 剑指Offer之面试题1:赋值运算符函数
- 剑指offer 面试题1:赋值运算符函数
- 剑指Offer:面试题01---赋值运算符函数
- 剑指offer面试题(一):赋值运算符函数
- 剑指offer:面试题一:赋值运算符函数
- 剑指offer,面试题一:赋值运算符函数
- 剑指offer面试题 赋值运算符函数
- 《剑指Offer》面试题一之赋值运算符函数
- 剑指offer面试题之赋值运算符函数
- 剑指offer 面试题1:赋值运算符
- POJ 3253 Fence Repair(优先队列)
- C++中的浅拷贝和深拷贝
- 不规则Image
- *LeetCode 79. Word Search DFS
- 机器学习算法选择
- 剑指offer-面试题1:赋值运算符函数
- Spark Streaming和Flume集成指南V1.4.1
- 拉格朗日插值法复习小计
- SDK 开发中见到的问题
- Jersey项目从Tomcat8到Glassfish4.1.1
- vim 基础篇
- oracle中REGEXP_SUBSTR方法的使用
- MySQL日期和时间类型
- AIM Tech Round (Div. 2) 解题报告