question1 赋值运算操作符
2024-09-07 01:52:52
注意的问题书上讲的很详细了
下面是代码实现,但是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 ;
}
最新文章
- atom配置web开发环境
- eventbus 备注
- NewBluePill源码学习
- 创建javascript对象的几种方式
- 全站HTTPs,没那么简单
- 161215、MySQL 查看表结构简单命令
- ASP.NET Web Forms的改进
- hdu 3804 树链剖分
- 【原】WinForm中的DataGridView加入Combbox或者DropDownButton后,操作变慢
- UVa 116 (多段图的最短路) Unidirectional TSP
- 『C # 开发』技能 Get√ ——制作CMD界面的简单GIF图片
- 開始学习swift开发
- Qt Label show Images
- Win10下python3和python2同时安装并解决pip共存问题
- 【转】git示意图
- 6月19 使用tp框架生成验证码及文件上传
- mybatis由浅入深day02_8spring和mybatis整合
- [Grunt] Minifying your output with grunt-uglify
- Python学习:12.Python字符串格式化
- Apache的Mod_rewrite学习 (RewriteCond重写规则的条件) 转