2、实现一个自定义的字符串类String。
i. 定义具有两个私有数据成员,分别表示字符串的存储地址(char*类型)和长度(int类型)。实现字符串类String的构造函数、析构函数、拷贝构造函数、赋值运算。
ii. 实现运算符重载:String + String、String + char *
iii. 重载运算符 << 和 >> ,实现字符串的输入和输出。
iv. 在main函数写一段简单的使用该字符类(包含上述运算)的测试程序
test.cpp
#include"string.h"
#include<iostream>
using namespace std;
int main()
{
String s1, s2;
s1 = "chenhaoran";
s2 = "zhangchao";
cout << s1<<endl;
String s3(s2);
cout << s3<<endl;
String s4 = s3;
cout << s4 << endl;
//cout << s4 + s2 << endl;
String s6 = s4 + s2;
s1 = s4 + s2;//这不是调用复制构造函数
cout << s6 << endl;
return 0;
}
string.h
#pragma once
#include<ostream>
#include<istream>
using namespace std;
class String {
private:
char *_str;
int _size;
public:
String();
~String();
String(const String &s);
//friend String operator +(const String &temp1, const String &temp2);
//friend String operator +(const String &temp1, const char * temp2);
String operator+(const String &temp);
String operator+(const char *temp);
//String &operator =(String temp);
String &operator =(const char *temp);
friend ostream &operator<< (ostream &out, String &temp);//这里为什么是取地址符
friend istream &operator>>(istream &in,String &temp);
};
string.cpp
#include"string.h"
#include<string.h>
#include<iostream>
using namespace std;
String::String()
{
_str = new char[20];
_size = 0;
}
String::~String()
{
if (this->_str != NULL)
{
delete[] this->_str;
this->_str = NULL;
this->_size = 0;
}
}
String::String(const String &s)
{
int len = strlen(s._str);
_str = new char[len + 20];
strcpy(_str, s._str);
_size = s._size;
}
String String::operator+(const String &temp)
{
String *p=new String();
p->_str = new char[strlen(this->_str) + strlen(temp._str) + 1];
strcpy(p->_str, this->_str);
strcat(p->_str, temp._str);
return *p;
}
/*
String operator +(const String &temp1,const String &temp2)
{
//String temp(temp1);
String temp;
strcpy(temp._str, temp1._str);
//strcat(temp._str, temp1._str);
temp._size += temp1._size;
strcat(temp._str, temp2._str);
temp._size += temp2._size;
return temp;
}
String operator +(const String &temp1,const char *temp2)
{
String temp(temp1);
int len = strlen(temp2);
strcat(temp._str, temp2);
temp._size += len;
return temp;
}
*/
//String &String::operator=(String temp)
//{
// strcpy(this->_str, temp._str);
// this->_size = temp._size;
// return *this;
//}
String &String::operator=(const char *temp)
{
memset(this, '\0', this->_size);
strcpy(this->_str, temp);
this->_size = strlen(temp);
return *this;
}
ostream &operator<< (ostream &out,String &temp)
{
out << temp._str;
return out;
}
istream &operator>> (istream &in,String &temp)
{
in >> temp._size;
return in;
}