#include<iostream>
#include<string>
#include<cstring>
#include<cstdlib>
using namespace std;
const int LIMIT = 100;
class NewString
{
private:
char* str;
int len;
public:
NewString() :str(nullptr), len(0) {}
NewString(const char*);
~NewString();
NewString(const NewString&);
friend istream& operator>>(istream&, NewString&);
friend ostream& operator<<(ostream&, const NewString&);
NewString operator+(NewString&);
NewString& operator=(const NewString&);
char& operator[](int);
int size();
};
NewString::NewString(const char* one)
{
this->len = strlen(one);
this->str = new char[len + 1];
strcpy_s(this->str, len + 1, one);
}
NewString::~NewString()
{
delete[] this->str;
this->str = nullptr;
}
NewString::NewString(const NewString& one)
{
this->len = one.len;
this->str = new char[len + 1];
strcpy_s(this->str, len + 1, one.str);
}
NewString& NewString::operator=(const NewString& one)
{
if (this != &one)
{
delete[] this->str;
this->len = one.len;
this->str = new char[len + 1];
strcpy_s(this->str, len + 1, one.str);
}
return *this;
}
istream& operator>>(istream& os, NewString& one)
{
char store[LIMIT];
os.getline(store, LIMIT);
delete[] one.str;
one.len = strlen(store);
one.str = new char[one.len + 1];
strcpy_s(one.str, one.len + 1, store);
return os;
}
ostream& operator<<(ostream& os, const NewString& one)
{
os << one.str;
return os;
}
NewString NewString::operator+(NewString& one)
{
NewString sum;
sum.len = strlen(this->str) + strlen(one.str);
sum.str = new char[sum.len + 1];
memset(sum.str, 0, sum.len + 1);
strcpy_s(sum.str, sum.len + 1, this->str);
strcat_s(sum.str, sum.len + 1, one.str);
return sum;
}
int NewString::size()
{
return this->len;
}
char& NewString::operator[](int n)
{
if (n >= this->len || n < 0)
{
cout << "error!" << endl;
exit(EXIT_FAILURE);
}
else
{
return this->str[n];
}
}
注意strcpy_s,strcat_s的用法,strcat_s使用前的memset初始化