刚学了操作符重载,自己试着练习了一下
#include<iostream>
#pragma warning (disable:4996)
using namespace std;
class mystring {
friend ostream& operator<<(ostream &os, mystring const& string1);
friend istream& operator>>(istream &os, mystring& string);
public:
mystring() {
this->len = 0;
this->string = NULL;
}
mystring(mystring const& another) {
len = another.len;
string = new char[len + 1];
strcpy(string,another.string);
}
mystring(char const* another) {
if (another == NULL) {
len = 0;
string = NULL;
}
else {
len = strlen(another);
string = new char[len + 1];
strcpy(string, another);
}
}
mystring(int len) {
this->len = len;
string = new char[len + 1];
memset(this->string, 0, len + 1); //将此空间全部清零
}
mystring operator+(mystring another) {
mystring temp(len + another.len);
strcpy(temp.string, string);
strcat(temp.string, another.string);
return temp;
#if 0
mystring temp;
temp.len = this->len + another.len;
temp.string = new char[(temp.len) + 1];
strcpy(temp.string, string);
strcat(temp.string,another.string);
return temp;
#endif
}
char& operator[](int i) {
return this->string[i];
}
bool operator==(const mystring &another)
{
if (strcmp(this->string, another.string) == 0) {
return true;
}
else {
return false;
}
}
bool operator!=(const mystring &another)
{
return !(*this == another);
}
private:
int len;
char* string;
};
ostream& operator<<(ostream &os, mystring const & string) {
os << string.string;
return os;
}
istream& operator>>(istream &is, mystring& string) {
if (string.string != NULL) {
delete[] string.string;
}
char temp[2048] = { 0 };
is >> temp;
string.len = strlen(temp);
string.string = new char[string.len+1];
strcpy(string.string, temp);
return is;
}
int main() {
mystring A("abc");
mystring B = A;
cout << A << endl;
cout << B << endl;
cout << (A + B) << endl;
B[1] = 'g';
cout << B << endl;
cout << "输入B的新值:";
cin >> B;
cout << B << endl;;
if (A == B) {
cout << "输入的B和A相等" << endl;
}
else {
cout << "输入的B和A不相等" << endl;
}
system("pause");
return 0;
}