C++中常见的运算符重载
作为一个C++的菜鸡初学者,每次用到运算符重载的时候都需要再重新查一遍。不如一次总结好,把运算符重载相关的部分写成一个例子:
#include<iostream>
using namespace std;
class complex
{
public:
double real;
double imag;
complex(double a,double b):real(a),imag(b){}
complex():real(0),imag(0){} //这里一定要写
complex operator+(const complex& A) { //对+进行重载
complex B;
B.real = this->real + A.real;
B.imag = this->imag + A.imag;
return B;
}
complex operator -(const complex& A) { //对-进行重载
complex B;
B.real = this->real - A.real;
B.imag = this->imag - A.imag;
return B;
}
complex operator ++(int) {
this->real = this->real + 1;
return *this;
}
friend bool operator >(const complex &A, const complex& B) { //对>进行重载
if (A.real > B.real)
{
return true;
}
else
{
return false;
}
}
friend bool operator <(const complex& A, const complex& B) { //对<进行重载
if (A.real < B.real)
{
return true;
}
else
{
return false;
}
}
friend ostream &operator <<(ostream& os,const complex& A) //对于流运算符进行重载
{
os << "After operator:real:" << A.real << " imagine:" << A.imag;
return os;
}
void PrintMessage()
{
cout << "Real:" << this->real << endl;
cout << "Imagine:" << this->imag << endl;
}
};
int main()
{
complex A(1, 2);
complex B(3, 4);
if (A > B)
{
cout << "A>B" << endl;
}
else
{
cout << "A<B" << endl;
}
complex C = A + B;
complex D = A - B;
cout << A << endl;
A++;
A.PrintMessage();
C.PrintMessage();
D.PrintMessage();
cout << endl;
}
运行结果
写在最后:
- 对于流运算符为什么必须使用friend友元,我个人的理解是(欢迎大佬来指正)ostream中的对象,如本次使用的os,相对于complex来说属于类外成员,因此需要使用friend。
- 对于流云算为什么必须使用引用类型(ostream& os)和&operator,在多个平台查了查,ostream对象不支持复制,需要是引用(欢迎大佬来指正)。
- 参与运算符重载的至少有一个类。
- 大多数的运算符是可以重载的,但::(域运算符),.*(成员指针运算符),sizeof,?:(条件运算符)(在网上查了一下才知道名字,捂脸.jpg)不可以重载。
- 重载运算符不会改变运算符的优先级和其结合性。
- 重载函数可以定义在类内,当然也可以定义为一个友元函数。
补充:流运算符重载
#include<iostream>
using namespace std;
class A
{
public:
int x;
int y;
A(int a=2,int b=3):x(a),y(b){}
friend istream& operator>>(istream& is, A& a) //流提取运算符 >> 重载
{
is >> a.x >> a.y;
return is;
}
friend ostream& operator<<(ostream& os,const A& a) //流插入运算符 >> 重载
{
os << a.x << " " << a.y << endl;
return os;
}
void print_a()
{
cout << x << " " << y << endl;
}
};
int main()
{
A a;
cout << a;
cin >> a;
cout << a;
return 0;
}