注意的问题书上讲的很详细了
下面是代码实现,但是VS有一个问题,strcpy安全性较低,虽然可以通脱编译,但是运行会报错,提示用strcpy_s()替代,但是,这里用strcpy()替代也不行,
//题目:如下为类型CMyString的声明,请为该类型添加赋值运算符
//以下为完整代码和测试用例
#pragma warning(disable:4996)
#include
#include
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 ;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章