一.重载运算符的简单介绍
顾名思义,是将运算符的运算规则重新进行规定。 本质上是一个会自动进行调用的函数!
文章接下来会按照以下几点来讲:
1.重载运算符在代码形式上分为:类内重载 与 类外重载
;
2.针对被重载运算符的类型来讲主要分为:单目,双目运算符的重载;
3.关于这部分知识点需要特别注意的有:1.++对象,对象++ 既前置与后置的区分 2.输入与输出的重载;
4.原理的简单讲解;
二.重载运算符的使用
1.按照代码形式
类内:
class test
{
返回类型 operator 被重载的运算符 (形参类型 形参名)
{
函数体
}
};
类外:
与友元函数联用
class test
{
friend 返回类型 operator 被重载的运算符 (形参类型 形参名)
};
返回类型 operator 被重载的运算符 (形参类型 形参名)
{
函数体
}
两种形式均可,但都要会,个人推荐第一种。
2.按照被重载运算符的类型上来分
注意:接下来会针对+ ++(前置) ++(后置) << >> 共5个运算符进行代码举例,每一段距离的过程不仅有代码例子也会有相应的解释。
1.基础类型
“+”
#include <iostream>
using namespace std;
class A
{
int x;
int y;
public:
A()
{
cin>>x>>y;
}
A operator + (A &a)
{
a.x+=this->x;
a.y+=this->y;
return a;
}
void show()
{
cout<<x<<" "<<y<<endl;
}
};
int main()
{
A a,b;
a.show();
a=a+b;
a.show();
}
运行结果:
1 1
2 2
1 1
3 3
Process returned 0 (0x0) execution time : 3.261 s
Press any key to continue.
2.输入流>>
注:输入i和输出o都建议用友元函数重载
先等等!!问你个问题哦,可有想过为啥你加一个头文件叫iostream吗?
#include <iostream>
using namespace std;
class A
{
int x;
int y;
public:
A()
{
cin>>x>>y;
}
friend istream &operator >> (istream &in,A &a);
void show()
{
cout<<x<<" "<<y<<endl;
}
};
istream &operator >> (istream &in,A &a)
{
in>>a.x>>a.y;
return in;
}
int main()
{
A a;
a.show();
cin>>a;
a.show();
}
1 1
1 1
1 2
1 2
Process returned 0 (0x0) execution time : 4.028 s
Press any key to continue.
3. 输出流 <<
#include <iostream>
using namespace std;
class A
{
int x;
int y;
public:
A()
{
cin>>x>>y;
}
friend ostream &operator << (ostream &out,A &a);
void show()
{
cout<<x<<" "<<y<<endl;
}
};
ostream &operator << (ostream &out,A &a)
{
out<<a.x<<a.y;
return out;
}
int main()
{
A a;
a.show();
cout<<a<<endl;
}
运行结果
1 1
1 1
11
Process returned 0 (0x0) execution time : 2.112 s
Press any key to continue.
到这里,如果你对<< 和>>重载为什么要用类外重载,而不能直接类内重载有困惑而且非常渴望知道的话,请先看四
注意:这里的形参表中数据顺序不可颠倒。
4.++前置
单目运算符
#include <iostream>
using namespace std;
class a
{
int x;
public :
a()
{
cin>>x;
}
void operator ++ ()
{
this->x++;
}
void show()
{
cout<<x<<endl;
}
};
int main()
{
a a1;
a1.show();
++a1;
a1.show();
}
5.++后置
#include <iostream>
using namespace std;
class Complex
{
private:
int x;
public:
Complex(int x)
{
this->x=x;
}
Complex operator++(int)
{
this->x++;
Complex tmp = *this;
return tmp;
}
void show()
{
cout<<x<<endl;
}
};
int main()
{
Complex c1(1);
c1++;
c1.show();
return 0;
}
后置就是多了个int的标志符号,这个int在这里仅仅作为标志,标志着++是后置的。
四
讲了这么多,可知道重载函数是怎么实现的吗?
用<<举例
我们知道成员函数有一个隐藏的参数this,它在我们自己定义的参数之前,
那么如果我们真的使用成员函数进行重载
ostream & operator <<(ostream & cout);
看上去是这样,但实际上是下面这样
ostream & operator <<(myclass * this, ostream & cout);
所以用起来就应该是
sth << cout;
但是这也太别扭了吧
所以我上面才说建议使用,而没说只能使用,“你这样做当然可以但不是最优解”