需要解决的问题
下面的复数解决方案是否可行
复数的加法操作
30-1.cpp
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA() const
{
return a;
}
int getB() const
{
return b;
}
friend Complex Add(const Complex& p1, const Complex& p2);
};
Complex Add(const Complex& p1, const Complex& p2)
{
Complex ret;
ret.a = p1.getA() + p2.getA();
ret.b = p1.getB() + p2.getB();
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = Add(c1, c2); // c1 + c2
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
结果:
c3.a = 4,c3.b =6
思考
在上面的编程demo中Add函数解决了Complex对象相加的问题,但是Complex是现实世界中确实存在的复数,并且复数在数学中地位和普通函数的实数相同,为什么不让+操作符也支持复数相加昵
操作符重载
C++中的重载能够扩展操作符的功能,操作符重载以函数的方式进行
本质:
用特殊形式的函数扩展操作符的功能
操作符重载初探
全局函数版本:
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA() const
{
return a;
}
int getB() const
{
return b;
}
friend Complex operator+(const Complex& p1, const Complex& p2);
};
Complex operator+(const Complex& p1, const Complex& p2)
{
Complex ret;
ret.a = p1.getA() + p2.getA();
ret.b = p1.getB() + p2.getB();
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 =c1+c2; // // operator + (c1, c2)
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
结果:
c3.a = 4,c3.b =6
可以将操作符重载函数定义为类的成员函数
比全局操作符重载函数少一个参数(左操作数)this充当左操作数
不需要依赖友元就可以完成操作符重载
编译器优先在成员函数中寻找操作符重载函数
成员函数版本:
30.3.cpp
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA() const
{
return a;
}
int getB() const
{
return b;
}
Complex operator+(const Complex& p1)
{
printf("Complex & operator+(const Complex& p1)\n");
Complex ret;
ret.a = p1.a + this->a;
ret.b = p1.a + this->b;
return ret;
}
friend Complex operator+(const Complex& p1, const Complex& p2);
};
Complex operator+(const Complex& p1, const Complex& p2)
{
Complex ret;
ret.a = p1.getA() + p2.getA();
ret.b = p1.getB() + p2.getB();
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 =c1+c2; // c1 + c2
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
结果:
小结
- operaor关键字是实现操作符重载的关键
- 全局函数与成员函数都可以实现对操作符的重载