在C++中封装一个String类,实现字符的比较和赋
思路:主要是利用重载运算符的知识,对运算符进行重载实现string类的功能。
(1)构造类
#include <iostream>
#include <string.h>
using namespace std;
class Mystring { //string类
public:
Mystring(char *str) : str(str)//构造传字符串地址
{
len = strlen(str);
}
~Mystring()
{
}
public:
string getstr() //输出打印
{
return str;
}
friend Mystring operator + (Mystring &a, Mystring &b);//友元函数重载+声明
Mystring operator = (Mystring &b);//成员函数重载 = 声明
bool operator == (Mystring &b);//成员函数重载==声明
bool operator != (Mystring &b);//成员函数重载!=声明;
private:
char *str;
int len;
};
(2)友元函数重载+运算符
Mystring operator + (Mystring &a, Mystring &b)
{
Mystring temp = "";
temp.len = a.len + b.len;
temp.str = new char[temp.len + 1]; //开辟拼接字符串大小的空间
strcpy(temp.str, a.str);
strcat(temp.str, b.str);
return temp;
}
(3)成员函数重载=运输符
Mystring Mystring::operator = (Mystring &b)
{
Mystring temp = "";
temp.len = b.len;
temp.str = new char[temp.len + 1];
strcpy(temp.str, b.str);
return temp;
}
(4)成员函数重载==运算符
bool Mystring::operator == (Mystring &b)
{
if (strcmp(this->str, b.str))
return false;
else
return true;
}
(5)成员函数重载!=运算符
bool Mystring::operator != (Mystring &b)
{
if (strcmp(this->str, b.str))
return true;
}
(6)验证
int main()
{
Mystring a = "hello",b = "hello worold";
Mystring d = a + b;
cout << d.getstr() << endl;//验证a + b
a = b;
cout << a.getstr() << endl;//验证a = b
if (a == b) cout << "相等" << endl;
else cout << "不相等" << endl;
cout << a.getstr() << endl;//验证a
cout << b.getstr() << endl;//验证b
if (a != b) cout << "不相等" << endl;
else cout << "相等" << endl;
return 0;
}