剑指offer——赋值运算符函数
来源:互联网 发布:我赢职场java视频下载 编辑:程序博客网 时间:2024/06/01 07:40
#include<iostream>using namespace std;class String{public: String(char * pData = NULL); String(const String& str); ~String(); String& operator=(const String& str); void print();private: char * m_pData;};String::String(char * pData){ if (pData == NULL) { m_pData = new char[1]; m_pData[0] = '\0'; } else { int length = strlen(pData); m_pData = new char[length + 1]; strcpy(m_pData, pData); }}String::String(const String& str){ int length = strlen(str.m_pData); m_pData = new char[length + 1]; strcpy(m_pData, str.m_pData);}String::~String(){ delete[] m_pData;}/*//常规方法String& String::operator=(const String& 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;}*//*//先分配,再释放String& String::operator=(const String& str){ if (this == &str) return *this; char * temp = new char[strlen(str.m_pData) + 1];; delete[] m_pData; m_pData = temp; strcpy(m_pData, str.m_pData); return *this;}*///创建临时变量String& String::operator=(const String& str){ if (this == &str) return *this; String ss(str); char * temp = ss.m_pData; ss.m_pData = m_pData; m_pData = temp; return *this;}//测试代码void String::print(){ cout << m_pData << endl;}void Test1(){ cout << "Test1 begins:\n"; char * text = "hello world"; String str1(text); String str2; str2 = str1; cout << "The expected result is: " << text << endl; cout << "The actual result is:"; str2.print(); cout << endl;}//赋值给自己void Test2(){ cout << "Test1 begins:\n"; char * text = "hello world"; String str1(text); str1 = str1; cout << "The expected result is: " << text << endl; cout << "The actual result is:"; str1.print(); cout << endl;}//连续赋值void Test3(){ cout << "Test1 begins:\n"; char * text = "hello world"; String str1(text); String str2, str3; str3 = str2 = str1; cout << "The expected result is: " << text << endl; cout << "The actual result is:"; str2.print(); cout << endl; cout << "The expected result is: " << text << endl; cout << "The actual result is:"; str3.print(); cout << endl;}int main(){ Test1(); Test2(); Test3(); return 0;}
阅读全文
0 0
- 《剑指offer》——重载赋值运算符函数
- 剑指offer——赋值运算符函数
- 【剑指offer】赋值运算符函数_01
- 【剑指Offer】赋值运算符函数
- 【剑指offer】1.赋值运算符函数
- 剑指offer - 赋值运算符函数
- 《剑指offer》01 赋值运算符函数
- 剑指offer--赋值运算符函数
- 剑指offer-01:赋值运算符函数
- 剑指offer——面试题1:赋值运算符函数
- 剑指offer 赋值运算符
- 剑指Offer算法实现之一:赋值运算符函数
- 剑指Offer:面试题01---赋值运算符函数
- 剑指offer面试题(一):赋值运算符函数
- 剑指offer:面试题一:赋值运算符函数
- 《剑指Offer》面试题1:赋值运算符函数
- 剑指Offer系列---(3)赋值运算符函数
- 剑指offer:面试题1 赋值运算符函数
- 45. Jump Game II
- mybatis完整配置详解
- 测试网站:http://001.lostcity.com
- Unity调试shader
- springmvc中遇到的问题
- 剑指offer——赋值运算符函数
- 多线程编程学习一(Java多线程的基础)
- java web项目资源位置
- ADS131A02驱动调试笔记(stm32f407+spi)
- Eclipse工程启动错误:ClassNotFoundException-Log4jConfigListener
- hdu 4407 Sum(容斥原理+数论)
- bzoj1984 月下“毛景树”(边权的树链剖分)
- Android LayoutInflater开发中的用法
- 8、js基础:闭包