//运算符重载
//不能重载的运算符 :: . .* ?: sizeof
//
#include<iostream>
using namespace std;
class Complex
{
friend ostream& operator<<(ostream& out, Complex c);
friend Complex operator+(const Complex& c1, const Complex& c2);
friend Complex operator-(const Complex& c2);
double m_real;
double m_vir;
public:
Complex(double real = 0, double vir = 0) :m_real(real), m_vir(vir) {}
void print()
{
cout << m_real << "+" << m_vir << "i" << endl;
}
Complex operator-(const Complex& c2)
{
cout << "成员重载" << endl;
Complex temp;
temp.m_real = this->m_real - c2.m_real;
temp.m_vir = this->m_vir - c2.m_vir;
return temp;
}
Complex& operator++(int)
{
this->m_real++;
this->m_vir++;
return *this;
}
//重载后++
Complex operator++()
{
Complex c = *this;
this->m_real++;
this->m_vir++;
return c;
}
};
Complex operator+(const Complex& c1, const Complex& c2)
{
cout << "外面的" << endl;
Complex temp;
temp.m_real = c1.m_real + c2.m_real;
temp.m_vir = c1.m_vir + c2.m_vir;
return temp;
}
ostream& operator<<(ostream& out, Complex c)
{
out << c.m_real<<" +" << c.m_vir<<"i";
return out;
}
int main()
{
Complex cp1(1, 2);
Complex cp2(3, 4);
Complex cp3;
//双目 用友元重载 左操作数做第一参数 右操作数做第二参数
cp3 = cp1 + cp2;//cp3=operator+(cp1,cp2)
cp3.print();
//cp3 = cp2 - cp1;
cp3 = cp2.operator-(cp1);
cp3.print();
cout << "-------------------------------" << endl;
//单目 ++ --
//单目用友元 只有一个参数 操作数就是参数
//用成员函数 没有参数(有一个隐藏this)
cout << ++cp3 << endl;
cout << cp3++ << endl;
cout << cp3 << endl;
return 0;
}
C++运算符重载
最新推荐文章于 2024-10-16 22:34:48 发布