注意的问题书上讲的很详细了

下面是代码实现,但是VS有一个问题,strcpy安全性较低,虽然可以通脱编译,但是运行会报错,提示用strcpy_s()替代,但是,这里用strcpy()替代也不行,

 //题目:如下为类型CMyString的声明,请为该类型添加赋值运算符
//以下为完整代码和测试用例
#pragma warning(disable:4996)
#include <iostream>
#include <cstring>
using namespace std;
class CMyString {
public:
CMyString(char* pData = nullptr);
CMyString(const CMyString& str);
~CMyString(void);
// operator "="
CMyString& operator =(const CMyString& str);
void print();//用来输出测试结果
private:
char*m_pData;
}; //the defination of the constructor fun
CMyString::CMyString(char* pData)
{
if (pData == nullptr)
m_pData = new char[];
m_pData[] = '\0';
} CMyString::CMyString(const CMyString& str)
{
int len = strlen(str.m_pData);
m_pData = new char[len + ];
//m_pData(str.m_pData);
strcpy(m_pData, str.m_pData); } CMyString::~CMyString()
{
//delete m_pData[];
delete[]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) + ];
strcpy(m_pData, str.m_pData);
return *this; } void CMyString:: print()
{
cout << m_pData << endl;
}
//测试用例 void test1()
{
char* str = "Hello World!";
CMyString str1(str);
CMyString str2;
str2 = str1;//call CMystring& operator=(const CMyString& str)
cout << " str is : " << str << endl;
//cout << "str2 is : " << str2.print() << endl;//没有重载<<运算符,还不能用
cout << "after 赋值" <<"str2 is : "<< endl;
str2.print();
} void test2()//赋值给自己
{
char* str = "Hello world!";
CMyString str1(str);
str1=str1;
cout << " str is : " << str << endl; cout << "after 赋值" << "str1 is : " << endl;
str1.print(); } void test3()//连续赋值
{
char* str = "Hello World!";
CMyString str1(str);
CMyString str2, str3;
str3 = str2 = str1;
cout << "str1 is : " << endl;
str1.print();
cout << "str2 is : " << endl; str2.print();
cout << "str3 is : " << endl;
str3.print();
} int main()
{
test1();
test2();
test3();
system("pause");
return ;
}

最新文章

  1. atom配置web开发环境
  2. eventbus 备注
  3. NewBluePill源码学习
  4. 创建javascript对象的几种方式
  5. 全站HTTPs,没那么简单
  6. 161215、MySQL 查看表结构简单命令
  7. ASP.NET Web Forms的改进
  8. hdu 3804 树链剖分
  9. 【原】WinForm中的DataGridView加入Combbox或者DropDownButton后,操作变慢
  10. UVa 116 (多段图的最短路) Unidirectional TSP
  11. 『C # 开发』技能 Get√ ——制作CMD界面的简单GIF图片
  12. 開始学习swift开发
  13. Qt Label show Images
  14. Win10下python3和python2同时安装并解决pip共存问题
  15. 【转】git示意图
  16. 6月19 使用tp框架生成验证码及文件上传
  17. mybatis由浅入深day02_8spring和mybatis整合
  18. [Grunt] Minifying your output with grunt-uglify
  19. Python学习:12.Python字符串格式化
  20. Apache的Mod_rewrite学习 (RewriteCond重写规则的条件) 转

热门文章

  1. 找到第N个字符
  2. 翻页插件 jquery
  3. 【SSM 项目】实战总结
  4. iOS ViewController 中代码书写规范
  5. stm32CubeMx lwip + freeRTOS
  6. spring aop @after和@before之类的注解,怎么指定多个切点
  7. Python3.5学习之旅——day4
  8. 输入url到展示页面过程发生了什么?
  9. Ubuntu 16.04 安装Redis服务器端
  10. DNS域名解析,内网