1、自定义一个字符串类MyString,用来存放不定长的字符串,重载运算符“==”、“+”,用于两个字符串的内容比较,初值自拟。测试比较两个字符串内容是否相同。
代码示例:
#include <iostream>
#include <cstring>
using namespace std;
class MyString{
friend ostream &operator<<(ostream &os,const MyString &other);
private:
char *str;
public:
MyString():str{}{}
MyString(const char *s){//字符数组初始化
str = new char[strlen(s) + 1];//创建新的堆空间,长度strlen(s)+1,1是因为还有‘\0’字符
strcpy(str,s);//将字符数组s中的值赋值到str中
}
MyString operator+(const MyString &other){
char *newStr = new char[strlen(this->str) + strlen(other.str) + 1];//申请新的堆空间,包含两个字符串
strcpy(newStr,str);//将str字符串复制到newStr
strcat(newStr,other.str);//将other.str字符串拼接到newStr字符串末尾
MyString str{newStr};//初始化字符串str,并赋值newStr字符串(为什么不直接输出newStr字符指针,是因为要释放掉newStr指针,但又需要字符串的值,所以直接初始化str,后面程序结束会自动调用析构函数)
delete[] newStr;//释放掉newStr字符指针
return str;
}
bool operator==(const MyString &other){
if(strcmp(other.str,this->str) == 0)
{
return true;
}
else
{
return false;
}
}
~MyString(){
delete[] str;//释放str
}
};
ostream &operator<<(ostream &os,const MyString &other)//<<左边的数据作为第一个参数,右边的数据作为第二个参数。
{
os<<other.str<<endl;
return os;//为了重复输出<<,需要返回os
}
int main()
{
MyString str1("hello");
MyString str2("world");
MyString str3 = str1 + str2;
if(str1 == str2)
{
cout<<"两个字符串相等"<<endl;
}
else
{
cout<<"两个字符串不相等"<<endl;
}
cout<<"str3 = "<<str3<<endl;
return 0;
}
运算结果:
两个字符串不相等
str3 = helloworld
2、定义一个复数类Complex,默认初始化为0,重载运算符“+”,“-”,使之能用于复数的加,减运算,运算符重载函数作为Complex类的成员函数。
代码示例:
#include <iostream>
#include <string>
using namespace std;
class Complex{
private:
int real;
int imag;
public:
Complex():real{},imag{}{}
Complex(int real,int imag):real{real},imag{imag}{}
Complex operator+(Complex &other)
{
Complex sum;
sum.real = this->real + other.real;
sum.imag = this->imag + other.imag;
return sum;
}
Complex operator-(Complex &other)
{
Complex diff;
diff.real = this->real - other.real;
diff.imag = this->imag - other.imag;
return diff;
}
void show()const
{
cout<<real<<(imag >= 0? "+":"")<<imag<<"i"<<endl;
}
};
int main()
{
Complex c1(3,4);
Complex c2(4,5);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
cout<<"两个复数的和是:";
c3.show();
cout<<"两个复数的差是:";
c4.show();
return 0;
}
运算结果:
两个复数的和是:7+9i
两个复数的差是:-1-1i