上课写的复数类的实现,再写一遍,写出三种构造函数,算术运算符、关系运算符、逻辑运算符重载尝试实现自增、自减运算符的重载
class Num
{
int rel; //实部
int vir; //虚部
public:
Num():rel(2),vir(1)
{cout << "Num的无参构造函数" << endl;}
Num(int rel,int vir):rel(rel),vir(vir)
{cout << "Num的有参构造函数" << endl;}
Num(const Num &other):rel(other.rel),vir(other.vir)
{cout << "Num的拷贝构造函数" << endl;}
Num &operator=(const Num &other)
{
cout << "Num的拷贝赋值函数" << endl;
this->rel = other.rel;
this->vir = other.vir;
return *this;
}
//全局函数版运算符重载
friend Num operator+(const Num n1,const Num n2);
friend Num operator*(const Num n1,const Num n2);
friend Num operator%(const Num n1,const Num n2);
//成员函数版的运算符重载
Num operator-(const Num n1);
Num operator/(const Num n1);
//全局函数版大于运算符重载
friend bool operator>(const Num n1,const Num n2);
//成员函数版小于运算符重载
bool operator<(const Num n1);
void show();
};
Num operator+(Num n1, Num n2)
{
Num temp;
temp.rel = n1.rel+n2.rel;
temp.vir = n1.vir+n2.vir;
return temp;
}
Num operator*(Num n1, Num n2)
{
Num temp;
temp.rel = n1.rel*n2.rel;
temp.vir = n1.vir*n2.vir;
return temp;
}
Num operator%(Num n1, Num n2)
{
Num temp;
temp.rel = n1.rel%n2.rel;
temp.vir = n1.vir%n2.vir;
return temp;
}
Num Num::operator-(Num n1)
{
Num temp;
temp.rel = this->rel-n1.rel;
temp.vir = this->vir-n1.vir;
return temp;
}
Num Num::operator/(Num n1)
{
Num temp;
temp.rel = this->rel/n1.rel;
temp.vir = this->vir/n1.vir;
return temp;
}
bool operator>(Num n1, Num n2)
{
if(n1.rel>n2.rel)
{
return n1.rel>n2.rel;
}else if(n1.rel == n2.rel)
{
return n1.vir>n2.vir;
}
return n1.rel>n2.rel;
}
bool Num::operator<(const Num n1)
{
if(this->rel<n1.rel)
{
return this->rel<n1.rel;
}else if(this->rel == n1.rel)
{
return this->vir<n1.vir;
}
return this->rel<n1.rel;
}
void Num::show()
{
cout << rel << "+" << vir << "i" << endl;
}
int main()
{
Num a1;
cout << endl;
Num a2(3,4);
cout << endl;
Num a3;
cout << endl;
a3 = a1+a2;
cout << endl;
a3.show();
cout << endl;
cout << (a1<a2) << endl;
return 0;
}