String类的重写

//头文件string.h

class String
{
public:
    String();
 String(char *str);

 ~String();
 String(const String &other);

 String & operator =(const String &other);  //赋值函数
 friend String operator +(const String &s1, const String &s2);

 void display(void);

private:
 char *m_data;
 int len;
};

//实现文件string.cpp
#include "String.h"
#include <iostream.h>
#include <string.h>

String::String()
{
 cout << "无参构造函数被调用" << endl;

 len = 0;
 m_data = new char[1];
 m_data[0] = '/0';
}

String::String(char *str)
{
    cout << "带参构造函数被调用" << endl;

 len = strlen(str);
 m_data = new char[len + 1];
 strcpy(m_data, str);
}

String::String(const String &other)
{
 cout << "拷贝构造函数被调用" << endl;

 len = other.len;
 m_data = new char[len + 1];
 
 strcpy(m_data, other.m_data);
}

String & String::operator =(const String &other)   //赋值函数
{
 cout << "重载 = 函数被调用" << endl; 

 if(this == &other)
 {
  return *this;
 }
 
 delete [] m_data;

 len = other.len;
 m_data = new char [len + 1];
 strcpy(m_data, other.m_data);

 return *this;

}

String::~String()
{
 cout << "析构函数被调用" << endl;
 delete [] m_data;
}

void String::display()
{
 cout << "m_data= " << m_data << "  len = " << len << endl;
}

String operator + (const String &s1, const String &s2)
{
 cout << "重载 + 函数被调用" << endl;
 
    String temp;
 
 delete temp.m_data;
 
 temp.len = s1.len + s2.len;
 temp.m_data = new char [temp.len + 1];
   
 strcpy(temp.m_data, s1.m_data);
 strcat(temp.m_data, s2.m_data);
 
    return temp;
}

//main.cpp

#include "String.h"
#include <iostream.h>

int main(void)
{
 String a ;
 String b("hello");
 String c(b);
 String d("ni hao");
 String e;

 a.display();
 b.display();
 c.display();
 d.display();
 e.display();

 cout << endl;
 
 a = d;
 a.display();
 
 cout << endl;

 e = b + d;
 cout << "here"<<endl;
 e.display();

 cout << endl;

 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值