运算符重载的实质:函数重载。除了增加一个关键字 operator 外,与函数重载没有区别,都是通过该类的某个对象来访问重载运算符。

(1)重载运算符时,运算符运算顺序和优先级不变操作数个数不变

(2)不能创造新的运算符;

(3)形式:重载为类的成员函数。对象本身就是其中的一个操作数,所以形参表内参数的数目比操作数的数目少一个

重载为类的友元函数。一元运算符有一个形参;二元运算符有两个形参;每个形参代表运算符的一个操作数。

 1、友元函数和成员函数的应用举例,一般情况下应用成员函数。

#include <iostream>
using namespace std; class Complex
{
public:
Complex(int a = , int b = )
{
this->a = a;
this->b = b;
}
void printCom()
{
cout << a << " + " << b << "i" << endl;
}
public:
// 友元函数实现,必须和实现的完全一样
friend Complex operator+(Complex &c1, Complex &c2);
friend Complex& operator++(Complex &c1);
friend Complex operator++(Complex &c1, int);
friend ostream& operator<<(ostream &out, Complex &c1);
//friend void operator<<(ostream &out, Complex &c1); //成员函数法实现 - 号运算符重载
Complex operator-(Complex &c2)
{
Complex tmp(a - c2.a, b - c2.b);
return tmp;
}
//成员函数实现 前置-- 操作
Complex& operator--()
{
a--; b--;
return *this;
}
//成员函数实现 后置-- 操作,与 前置-- 使用占位符进行区别。
Complex operator--(int)
{
Complex tmp = *this;
a--; b--;
return tmp;
}
private:
int a, b;
}; //友元函数实现 + 号运算符重载
Complex operator+(Complex &c1, Complex &c2)
{
Complex tmp(c1.a + c2.a, c1.b + c2.b);
return tmp;
}
// 友元函数实现 一元运算符 重载,前置++
Complex& operator++(Complex &c1)
{
c1.a++;
c1.b++;
return c1;
}
// 友元函数实现 一元运算符 重载,后置++
Complex operator++(Complex &c1, int)
{
Complex tmp = c1;
c1.a++;
c1.b++;
return tmp;
} void main()
{
Complex c1(, ), c2(, );
//1、全局函数实现,对于私有成员使用了友元函数。
Complex c3 = c1 + c2;
c3.printCom();
//2、成员函数实现
Complex c4 = c1 - c2;
c4.printCom(); //3、全局函数实现,前置++
++c1;
c1.printCom();
//4、成员函数实现,前置--
--c1;
c1.printCom(); //5、全局函数实现,后置++
Complex c5 = c1++;
c5.printCom();
c1.printCom();
//6、成员函数实现,后置--
Complex c6 = c1--;
c6.printCom();
c1.printCom(); system("pause");
}

2、友元函数的应用场景,左移右移操作符的重载。

//只能使用友元函数实现左移、右移操作运算符
/*oid operator<<(ostream &out, Complex &c1)
{
out << c1.a << " + " << c1.b << "i" << endl;
}*/
//只能使用友元函数实现左移、右移操作运算符
ostream& operator<<(ostream &out, Complex &c1)
{
out << c1.a << " + " << c1.b << "i" << endl;
return out;
} void main()
{
int a = ;
Complex c1(, ), c2(, );
//cout << c1;
cout << c1 << "abv" << endl;
system("pause");
}

最新文章

  1. 洛谷10月月赛Round.3
  2. java获取日期 昨天 今天 明天的日期
  3. [POJ 1385] Lifting the Stone (计算几何)
  4. php ftp文件上传函数--新手入门参考
  5. Maximum Product Subarray——LeetCode
  6. Android HandlerThread的用法
  7. SQL语法考核
  8. SCU 4438 Censor KMP/Hash
  9. 在Linux上安装Python3
  10. STM32F0使用LL库实现DMA方式AD采集
  11. [Android] Android Butterknife 8.8.1 在 Activity 和 Fragment 、 Adapter 中的使用
  12. tomcat部署应用时设置context path为空的上下文路径问题
  13. 【bzoj4530】[Bjoi2014]大融合 LCT维护子树信息
  14. visual studio属性管理器
  15. Dubbo剖析-SPI机制
  16. Python glob.md
  17. 构造函数constructor 与析构函数destructor(三)
  18. C#观察者模式的应用与思考
  19. ACM-ICPC2018 青岛赛区网络预赛-B- Red Black Tree
  20. es6 class 中 constructor 方法 和 super

热门文章

  1. accept 和 content-Type区别
  2. git bush 无法使用箭头进行选择
  3. node版本切换工具n的使用介绍
  4. Ingress 访问日志分析与监控
  5. mysql索引数据结构
  6. 【电商日志项目之五】数据分析-MR方式
  7. 最新 大众书网java校招面经 (含整理过的面试题大全)
  8. spring mvc 参数类型转换
  9. Git设定不合并的文件
  10. 【计算机网络基础】URI、URN和URL的区别