设计一个字符串类MyString,为其设计构造函数,析构函数和复制构造函数。重载运算符“+”,“=”,“+=”

本文深入探讨了使用C++实现自定义字符串类的方法,包括类的声明、构造函数、拷贝构造函数及析构函数的定义。核心部分详细讲解了运算符重载,特别是+=和+运算符的重载实现,展示了如何在类中实现字符串的连接操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 那我就废话少说,直接上代码

首先是类的声明,读者可把类名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();
}

 

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值