我们先来看下面这个例子是否能编译通过
实现复数的相加
#include <stdio.h>
class Complex
{
public:
int a;
int b;
};
int main()
{
Complex c1 = {1,2};
Complex c2 = {3,4};
Complex c3 = c1 + c2;
return 0;
}
结果:
sice@sice:~$ g++ c.cpp
c.cpp: 在函数‘int main()’中:
c.cpp:12:22: 错误: ‘operator+’在‘c1 + c2’中没有匹配
显然C++不支持这样对象直接相加
改进(1):
#include <stdio.h>
class Complex
{
private:
int a;
int b;
public:
Complex(int a=0,int b=0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
friend Complex Add(Complex &p1,Complex &p2);
};
Complex Add(Complex &p1,Complex &p2)
{
Complex ret;
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
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;
}
结果:
sice@sice:~$ ./a.out
c3.a = 4, c3.b = 6
缺点:但是还是感觉过于复杂,希望能直接使用+进行操作,这次改进不算成功,
升级:所以这里就引入了操作符重载
操作符重载
C++中的重载能够扩展操作符的功能
操作符的重载以函数的方式进行
本质:
用特殊形式的函数扩展操作符的功能
改进(2):
#include <stdio.h>
class Complex
{
private:
int a;
int b;
public:
Complex(int a=0,int b=0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
friend Complex operator +(Complex &p1,Complex &p2);
};
Complex operator +(Complex &p1,Complex &p2)
{
Complex ret;
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
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;
}
结果:
输出一致,当执行到c1+c2的时候,编译器就去找有没有+操作符的重载呢,发现找到该函数体,让+的左操作数和右操作数与函数参数列表比较是否匹配,匹配的话执行函数
缺点:
使用了友元,破坏了封装性
升级:
可以将操作符重载函数定义为类的成员函数,隐藏的this指针作为左操作数,对于操作符重载函数而言,成员函数优先级大于全局函数
改进(3):
#include <stdio.h>
class Complex
{
private:
int a;
int b;
public:
Complex(int a=0,int b=0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
Complex operator +(Complex &p2)
{
Complex ret;
ret.a = this->a + p2.a;
ret.b = this->b + p2.b;
return ret;
}
};
/*Complex operator +(Complex &p1,Complex &p2)
{
Complex ret;
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
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;
}
最后我们来实现一个完整的复数类
来源:CSDN
作者:勇士后卫头盔哥
链接:https://blog.csdn.net/qq_41936794/article/details/104654574