运算符重载:所谓重载,就是重新赋予新的含义。
不能重载的运算符有 . :: .* ?: sizeof
前置和后置运算符总结
C++中通过一个占位参数来区分前置运算和后置运算
代码实现 + << 和前置++ 后置++的运算符重载
#include <iostream>
using namespace std;
class Complex
{
//friend Complex operator +(Complex &c1,Complex &c2);
friend ostream &operator <<(ostream &out,const Complex &c);
private:
int m_a;
int m_b;
public:
Complex();
Complex(int a,int b);
void print();
Complex operator +( Complex &c2);
Complex operator ++(int);
Complex &operator ++();
};
Complex::Complex()
{
m_a = 0;
m_b = 0;
}
Complex::Complex(int a,int b)
{
m_a = a;
m_b = b;
}
/*void Complex::print()
{
cout << m_a << "+" << m_b << "i" << endl;
}*/
/*Complex operator +(Complex &c1,Complex &c2) //通过全局函数重载
{
Complex tmp;
tmp.m_a = c1.m_a + c2.m_a;
tmp.m_b = c1.m_b + c2.m_b;
return tmp;
}*/
Complex Complex::operator +(Complex &c2)
{
/*Complex tmp;
tmp.m_a = this->m_a + c2.m_a;
tmp.m_b = this->m_b + c2.m_b;
return tmp;*/
this->m_a = this->m_a + c2.m_a;
this->m_b = this->m_b + c2.m_b;
return *this;
}
ostream &operator <<(ostream &out,const Complex &c)
{
out << c.m_a << " + " << c.m_b << "i";
return out;
}
Complex Complex::operator ++(int)
{
Complex tmp = *this;
this->m_a++;
this->m_b++;
return tmp;
}
Complex& Complex::operator ++()
{
this->m_a++;
this->m_b++;
return *this;
}
int main()
{
Complex c1(1,2);
Complex c2(3,4);
/*Complex c3 = c1 + c2;
c3.print();
Complex c4 = c1.operator +(c2);
c4.print();*/
Complex c3;
c3 = c1 + c2;
cout << c3 << endl;
Complex c5;
c1 + c2 = c5;
cout << c1 << endl;
Complex c4;
cout << c4++ << endl;
cout << ++c4 << endl;
return 0;
}
== 和 != 运算符重载
clude <iostream>
using namespace std;
class Complex
{
private:
int m_a,m_b;
public:
Complex();
Complex(int a,int b);
bool operator ==(Complex &c);
bool operator !=(Complex &c);
};
Complex::Complex()
{
m_a = 0;
m_b = 0;
}
Complex::Complex(int a,int b)
{
m_a = a;
m_b = b;
}
bool Complex::operator ==(Complex &c)
{
if(this->m_a == c.m_a && this->m_b == c.m_b)
{
return true;
}
else
{
return false;
}
}
bool Complex::operator !=(Complex &c)
{
if(this->m_a != c.m_a || this->m_b != m_b)
{
return true;
}
else
{
return false;
}
}
int main()
{
Complex c1(1,2);
Complex c2(1,4);
if(c1 == c2)
{
cout << "相等" << endl;
}
else
{
cout << "不相等" << endl;
}
if(c1 != c2)
{
cout << "不相等" << endl;
}
else
{
cout << "相等" << endl;
}
return 0;
}
为什么不要重载&& 和 || 运算符
1)&&和||是C++中非常特殊的操作符
2)&&和||内置实现了短路规则
3)操作符重载是靠函数重载来完成的
4)操作数作为函数参数传递
5)C++的函数参数都会被求值,无法实现短路规则