C++重载操作符
问题1:是什么与为什么。
什么是重载,简单来说,就是同样一个函数,函数名相同,形参不同。比如我先做一个Max(int a,in b)比较大小的函数,紧接着我在做一个Max(int a,int = b,int c)的函数,这就进行了重载。
函数重载
int max(int a,int b)
{
return (a>b ? a :b);
}
int max(int a,int b,int c)
{
return (a>b ? a : (b > c ? b : c));
}
在函数调用到时候有一个参数匹配的搜索机制,搜索跟形参形式相同的那一个函数,从而实现了多态的作用。
那么重载操作符又是什么呢?C++的一个最显著的特点就是"类",而重载这些个操作符就是为类的对象服务,比如设计一个商品的类,商品A和商品B;通过重载操作符+,通过A+B我们可以设计将其总销售额返回,而不需要再访问其中的售价,售出数量。重载可以使我们的代码更精简,更加可读。
问题2.怎么办。
从一个虚数的计算开始,虚数有两个参数,实部和虚部,a+bi;我们实现虚数的加减乘除也就是在实部和虚部上面做手脚。
格式:
类型 operator 操作符(形参表)
下面是单文件实现虚数运算代码:
#include <iostream>
using namespace std;
struct complex
{
int real ;
int imag ;
};
//重载+号运算符
complex operator+( complex A,complex B)
{
complex c;
c.imag = A.imag + B.imag;
c.real = A.real + B.real;
return c;
}
//重载-号运算符
complex operator-( complex A,complex B)
{
complex c;
c.imag = A.imag - B.imag;
c.real = A.real - B.real;
return c;
}
//重载乘号运算符
complex operator*( complex A,complex B)
{
complex c;
c.imag = A.imag * B.real + A.real * B.imag;
c.real = A.real * B.real - A.imag * B.imag;
return c;
}
//重载>>
istream &operator>>(istream &is,complex &A)
{
is >> A.real >>A.imag;
return is;
}
//重载<<
ostream &operator<<(ostream &os,complex &A)
{
os << '('<<A.real<<','<<A.imag<<')'<<endl;
return os;
}
int main()
{
struct complex A = {0,0},B ={0,0},C;
cin >> A;
cin >> B;
C= A+B;
cout << "A + B = " <<C;
C = A-B;
cout << "A - B = " <<C;
C = A*B;
cout << "A * B = " <<C;
}
昨天晚上发现的问题:
在类里无法声明一个重载>>的函数,报错呢,报了一个operator调用了太多参数的问题,查找翻阅资料才知道,其实在C++类里重载函数默认有一个被操作数,就是这个类本身,比如A+B,其实是将B的东西加到A里面,默认被操作数是A。
istream &opertor >> (istream & is,book A);
ostream &opertor << (istream & is,book A);
怎么解决呢,友元函数!!!
还有为什么输入输出符的重载前面要加个&,我的理解是它要返回一个iostream的引用对象,我的理解,感觉应该对。