那我就废话少说,直接上代码
首先是类的声明,读者可把类名person换成MyString
#include<string>
#include <iostream>
using namespace std;
class person
{
public:
char* m_name;
void getname()
{
cout<< this->m_name;
}
person(const char* s)
{
cout << "一般构造函数被调用" << endl;
int len = strlen(s);
char* str = new char[2*len + 1];
strcpy_s(str, len + 1, s);
this->m_name = str;
}
person(const person& p1) //拷贝构造函数
{
this->m_name = p1.m_name;
}
~person( )
{
//delete this->m_name;
}
接下来是运算符重载,是代码的核心了
person& operator=(const person& p1)
{
this->m_name = p1.m_name;
return *this;
}
person operator+=(const person& p1)
{
int len = strlen(p1.m_name) + strlen(this->m_name);
char* str = new char[len + 1];
strcat_s(this->m_name,len+1, p1.m_name);
return *this;
}
person& operator+(const person& p1)
{
int len = strlen(p1.m_name) + strlen(this->m_name);
char* str = new char[len + 1];
strcat_s(this->m_name, len + 1, p1.m_name);
return *this;
}
};
最后就是main函数了,读者可以把test函数换成main函数里面
void test01()
{
person p1("hello");
person p2("world");
person p3("!!!!");
cout << (p1 + p2 + p3).m_name << endl;
cout << (p1 = p2 ).m_name<< endl;
p3 += p2;
cout << p3.m_name << endl;
}
int main()
{
test01();
}