双目运算符+和-号的重载
重载+号双目运算符
大体思路
+运算符的重载关键就在于“自定义该类的加法运算该如何进行”,下列代码展示了两个字符型数组的加法。
代码示例
#include <iostream>
#include <string>
using namespace std;
class MyString
{
private:
char *str1;
public:
MyString(char *str1)
{
this->str1 = new char[strlen(str1) + 1];
strcpy(this->str1, str1);
}
~MyString()
{
cout << "调用析构函数" << endl;
}
char* ReturnPointer()
{
return str1;
}
MyString& operator+ (MyString &mystr)
{
char *str = new char[strlen(str1) + strlen(mystr.ReturnPointer()) + 1];
strcpy(str, str1);
strcat(str, mystr.ReturnPointer());
str1 = str;
return *this;
}
void ShowInf()
{
cout << this->str1 << endl;
}
};
int main()
{
char str1[] = "aaa", str2[] = "bbb";
MyString mystr1(str1), mystr2(str2);
mystr1 + mystr2;
mystr1.ShowInf(); // 结果为aaabbb
}
重载-号双目运算符
大体思路
我想将两个对象的相同位置的相同字符去除,这就是我自定义的字符串数组的减法。重载+运算符的成员函数中包含用new申请的数组和for循环,用于把两个对象相同位置相同的字符取出来进行保存。
代码示例
#include <iostream>
#include <vector>
using namespace std;
class Mystring
{
private:
char *str;
public:
Mystring(char *str)
{
this->str = new char[strlen(str) + 1];
strcpy(this->str, str);
}
~Mystring()
{
cout << "调用析构函数" << endl;
}
char* ReturnPointer()
{
return this->str;
}
Mystring& operator- (Mystring &mystr)
{
char *Vstr = new char[strlen(this->str) + 1];
memset(Vstr, 0, strlen(this->str) + 1);
int j = 0;
for (int i = 0; i < strlen(this->str); i++)
{
if (str[i] != (mystr.ReturnPointer())[i])
{
Vstr[j++] = str[i];
}
}
strcpy(this->str, Vstr);
return *this;
}
void ShowInf()
{
cout << str << endl;
}
};
int main()
{
char str1[] = "asbd", str2[] = "absb";
Mystring mystr1(str1), mystr2(str2);
mystr1 - mystr2;
mystr1.ShowInf(); // 输出sbd
}
切记:用new申请了空间,必须到合适时机再用delete释放掉,new与delete必须成对出现,否则会造成内存被占用,浪费了宝贵的内存空间。