使用运算符重载简单实现string
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class myString {
private:
// 私有属性
char *str;
int size;
public:
//设置友元
friend ostream &operator<<(ostream &L, const myString &O);
friend istream &operator>>(istream &L, const myString &O);
// 无参构造
myString() : size(32) {
str = new char[size];
strcpy(str, "");
}
// 有参构造
myString(const char *s) {
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
//cout<<"str="<<str<<endl;
}
//拷贝构造(深拷贝)
myString(myString &other) {
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
}
//析构函数
~myString() {
delete[]str;
}
//判空函数
bool isEmpty() {
if (strlen(str) > 0) {
return false;
} else if (strlen(str) == 0) {
return true;
}
return false;
}
//size函数
int strSize() {
return size;
}
//c_str函数
char *c_str() {
return str;
}
//at函数
char &strAt(int index) {
if (index < 0 || index > size) {
cout << "下标不合法!";
return str[0];
}
return str[index];
}
//运算符重载
//等号
myString &operator=(const myString &R) {
size = R.size;
str = new char[size + 1];
strcpy(str, R.str);
return *this;
}
//中括号[]
char &operator[](int index) {
if (index < 0 || index > size) {
cout << "下标不合法!";
return str[0];
}
return str[index];
}
//加号
const myString operator+(const myString &R) const {
char *tmp = new char[this->size + R.size + 1];
strcpy(tmp, "");
strcpy(tmp, this->str);
// cout <<"1." << tmp << endl;
strcat(tmp, R.str);
// cout <<"2."<< tmp << endl;
return tmp;
}
//==等于号
bool operator==(const myString &R) const {
if (0 == strcmp(this->str, R.str)) {
return true;
} else {
return false;
}
}
//大于>
bool operator>(const myString &R) const {
if (0 < strcmp(this->str, R.str)) {
return true;
} else {
return false;
}
}
//小于<
bool operator<(const myString &R) const {
if (0 > strcmp(this->str, R.str)) {
return true;
} else {
return false;
}
}
};
//全局函数实现<<运算符实现
ostream &operator<<(ostream &L, const myString &O) {
L << O.str;
return L;
}
//全局函数实现<<运算符实现
istream &operator>>(istream &L, const myString &O) {
L >> O.str;
return L;
}
int main() {
char input[30] = "";
int index;
cout << "请输入一个字符串" << endl;
//获取字符串
fgets(input, sizeof(input), stdin);
input[strlen(input) - 1] = 0;
//getline(cin,input);
//初始化
myString str(input);
//拷贝
myString strcp(str);
//判空
cout << "判空:" << boolalpha << strcp.isEmpty() << endl;
//获取大小
cout << "大小:" << strcp.strSize() << endl;
//c_str
printf("str=%s\n", strcp.c_str());
//at函数
//cout<<"请输入字符串下标"<<endl;
//cin>>index;
index = 1;//设置下标为1
cout << str.strAt(index) << endl;//输出下标所在的字符
//测试<<运算符
cout << str << endl;
//赋值运算符
myString str1 = str;
cout << str1 << endl;
//中括号[]
str1[1] = 'A';
cout << "str1=" << str1 << endl;
//加号+
cout << (str + str1) << endl;
//<<运算符
cout << str << endl;
//>>运算符
cout << "请输入一个字符串" << endl;
cin >> str1;
cout << "str1=" << str1 << endl;
//大于
cout << "str是否大于str1?" << boolalpha << (str > str1) << endl;
//小于
cout << "str是否小于str1?" << boolalpha << (str < str1) << endl;
//等于
cout << "str是否等于str1?" << boolalpha << (str == str1) << endl;
}
现象: