//learnc160.h
/*
运算符重载,友元函数
*/
#ifndef LEARNC_16
#define LEARNC_16
class Number//声明类Number
{
private:
int num;
public:
Number(int n);
~Number();
Number operator+(const Number &n);// +运算符重载
Number operator-(const Number &n);// -运算符重载
Number operator*(const Number &n);// *运算符重载
Number operator/(const Number &n);// /运算符重载
friend Number operator+(int n,const Number &num);//友元函数
void showNum();
};
#endif // !LEARNC_16
//learnc161.cpp
#include<iostream>
#include "learnc160.h"
using std::cout;
using std::endl;
Number::Number(int n)
{
this->num = n;
}
Number::~Number()
{
}
Number Number::operator+(const Number &n)
{
Number number(0);
number.num = this->num + n.num;
return number;
}
Number Number::operator-(const Number &n)
{
Number number(0);
number.num = this->num - n.num;
return number;
}
Number Number::operator*(const Number &n)
{
Number number(0);
number.num = this->num * n.num;
return number;
}
Number Number::operator/(const Number &n)
{
Number number(0);
number.num = this->num / n.num;
return number;
}
void Number::showNum() {
cout << "num:" << this->num << endl;
}
Number operator+(int n, const Number &num) {
Number number(0);
number.num = n + num.num;
return number;
}
//learnc162.cpp
#include<iostream>
#include "learnc160.h"
int main()
{
Number n1 = Number(100);
Number n2 = Number(200);
Number n3 = n1 + n2;
Number n4 = n1 - n2;
Number n5 = n1 * n2;
Number n6 = n1 / n2;
n3.showNum();
n4.showNum();
n5.showNum();
n6.showNum();
/*
Number n = 1000 + n1;目前这种写法是不行的。
Number中的运算符重载后,左右两边必须都是Number类的对象,不能直接和一个int类型相加。
为了实现这个功能,就需要友元函数。
*/
Number n7 = 1000 + n1;
n7.showNum();
}
输出结果:
num:300
num:-100
num:20000
num:0
num:1100