1.运算符重载,当有的时候对象运算与正常运算符的操作意义相同时,为了代码的简洁,我们就可以使用运算符重载。
比如一个简单的加法操作,没有必要再写一个add方法,还是一个+看着比较顺眼。
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class A
{
private:
int num;
string name;
public:
A(int n){num = n;}
//一种重载方式,类的成员函数
A operator+ (A a)
{
a.num = this->num + a.num;
return a;
}
void Display()
{
cout<<num<<endl;
}
//友元函数重载,非成员函数设置为类的友元函数,以访问私有变量
friend A operator-(A, A);
};
A operator- (A a, A b)
{
a.num = a.num - b.num;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a(10);
A b(11);
(a + b).Display();
(a - b).Display();
getchar();
return 0;
}
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">运算符重载可以理解为:</span>
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);"> a+b <=>a.operator+(b)</span>
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">a - b <=> operator-(a, b)</span>
一个重载<<标准输出运算符的例子:
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class A
{
private:
int num;
public:
A(int n){num = n;}
//友元函数重载,非成员函数设置为类的友元函数,以访问私有变量
friend ostream& operator<<(ostream& os, A a);
};
ostream& operator<<(ostream& os, A a)
{
cout<<a.num;
return os;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a(10);
cout<<a<<endl;
getchar();
return 0;
}
重载==和!=运算符的例子:
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class A
{
private:
int num;
string name;
public:
A(int n, string na){num = n;name = na;}
//友元函数重载,非成员函数设置为类的友元函数,以访问私有变量
//重载==运算符
friend bool operator==(const A&, const A&);
//重载!=运算符
friend bool operator!=(const A&, const A&);
};
bool operator==(const A& a, const A& b)
{
return a.num == b.num && a.name == b.name;
}
bool operator!=(const A& a, const A& b)
{
//写好了就该用,开始自己差点重写了一个!=的单独的判断的。果然还是编程不够多啊。
return !(a==b);
}
int _tmain(int argc, _TCHAR* argv[])
{
A a(10, "haha");
A b(10, "haha");
if (a == b)
cout<<"a == b"<<endl;
else
cout<<"a != b"<<endl;
getchar();
return 0;
}