C++ string类的封装


//mystring.h   头文件

#ifndef _MYSTRING_H_

#define _MYSTRING_H_


#include <iostream>


using namespace std;


class String
{
friend ostream& operator<<(ostream &out,String &str);
public:
String( char *str);   //构造函数
String(const String &str);     //拷贝构造
~String();         //析构函数
String& operator=(const String &other);  //赋值运算符的重载

String& operator+(String &other);   //重载+(不改变被加对象)
void print();


private:
char *m_data;
};

#endif


//mystring.cpp  函数的实现

#include "mystring.h"
#include <iostream>
using namespace std;


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

int length=strlen(str);
m_data=new char[length+1];
strcpy(m_data,str);

}


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


String:: String(const String &str)
{
cout<<"拷贝构造函数被调用"<<endl;
int length=strlen(str.m_data);
m_data=new char[length+1];
strcpy(m_data,str.m_data);


}


String& String::operator=(const String &other)
{
cout<<"赋值运算符的重载"<<endl;
if(this == &other)
{
return *this;
}
delete []m_data;
int length=strlen(m_data);
m_data=new char[length+ 1];
strcpy(m_data,other.m_data);
return *this;
}


/*String& String::operator+(String &other)
{
char *temp=m_data;
m_data=new char[strlen(temp)+strlen(other.m_data)];
strcpy(m_data,temp);
delete []temp;
strcat(m_data,other.m_data);
return *this;
}*/


String& String::operator+(String& other)   //重载+(不改变被加对象)
{
String *pstring =new String("");    //堆内存中构造对象
pstring->m_data=new char [strlen(m_data)+strlen(other.m_data)+1];
strcpy(pstring->m_data,m_data);
strcat(pstring->m_data,other.m_data);
return *pstring;

}


void String::print()
{
cout<<m_data<<endl;

}


//main函数  

#include <iostream>
#include "mystring.h"
using namespace std;
ostream& operator<<(ostream& out,String &str)
{
int length=strlen(str.m_data);
for(int i=0;i<=length;i++)
{
out<<str.m_data[i]<<" ";
}
out<<endl;
return out;
}


int main ()
{
String a("hello");
String b("world");
String c=a;


c=c+b;
c.print();
c=c+a;
c.print();
c=a+b;
c.print();
a.print();
b.print();
cout<<c<<endl;


return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值