C++ 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载。
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。
// operatorOverload.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length *width*height;
}
void SetLength(double len)
{
length = len;
}
void SetWidth(double wid)
{
width =wid;
}
void SetHeight(double hei)
{
height = hei;
}
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.width = this->width + b.width;
box.height = this->height + b.height;
return box;
}
private:
double length;
double width;
double height;
};
class Distance
{
public:
Distance()
{
feet = 0;
inches = 0;
}
Distance(int f,int i)
{
feet = f;
inches = i;
}
//显示距离的方法
void displayDistance()
{
cout<<"F: "<<feet<<" I: "<<inches<<endl;
}
//重载负运算符(-)
Distance operator-()
{
feet = -feet;
inches = -inches;
return Distance(feet,inches);
}
//重载小于运算符 ( < )
bool operator < (const Distance &d)
{
if(feet <d.feet)
{
return true;
}
if(feet == d.feet && inches<d.inches)
{
return true;
}
return false;
}
//重载输入输出运算符 << >>
friend ostream &operator <<(ostream &output,const Distance &D)
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
friend istream &operator>>( istream &input, Distance &D )
{
input >> D.feet >> D.inches;
return input;
}
private:
int feet;
int inches;
};
void example1()
{
Box Box1;
Box Box2;
Box Box3;
double volume = 0.0;
// Box1
Box1.SetLength(6.0);
Box1.SetWidth(7.0);
Box1.SetHeight(5.0);
// Box2
Box2.SetLength(12.0);
Box2.SetWidth(13.0);
Box2.SetHeight(10.0);
// Box1 的体积
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// Box2 的体积
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// 把两个对象相加,得到 Box3
Box3 = Box1 + Box2;
// Box3 的体积
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
}
void example2()
{
Distance D1(11,10),D2(-5,11);
-D1;
D1.displayDistance();
-D2;
D2.displayDistance();
if(D1<D2)
{
cout<<"D1 is less than D2" <<endl;
}
else
{
cout<<"D2 is less than D1" <<endl;
}
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
}
int main()
{
example1();
example2();
system("pause");
return 0;
}