20、不一样的C++系列--操作符重载
来源:互联网 发布:师洋的淘宝店号是多少 编辑:程序博客网 时间:2024/06/06 07:07
操作符重载
- C++中的重载能够扩展操作符的功能
- 操作符的重载以函数的方式进行
- 本质:
- 用特殊形式的函数扩展操作符的功能
- 使用:
- 通过
operator
关键字可以定义特殊的函数 operator
的本质是通过函数重载操作符- 语法:
- 通过
Type operator Sign(const Type& p1, const Type& p2){ Type ret; return ret;}// Sign 为系统中预定义的操作符,如: +, -, *, /, 等
这里举一个例子:
#include <stdio.h>class Complex { int a; int b;public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } int getA() { return a; } int getB() { return b; } //声明操作符重载 friend Complex operator + (const Complex& p1, const Complex& p2);};//定义操作符重载Complex operator + (const Complex& p1, const Complex& p2){ Complex ret; //因为是友元,所以可以直接访问成员变量 ret.a = p1.a + p2.a; ret.b = p1.b + p2.b; return ret;}int main(){ Complex c1(1, 2); Complex c2(3, 4); Complex c3 = c1 + c2; // operator + (c1, c2) printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB()); return 0;}
另一种用法:
- 可以将操作符重载函数定义为类的成员函数
- 比全局操作符重载函数少一个参数(左操作数)
- 不需要依赖友元就可以完成操作符重载
- 编译器优先在成员函数中寻找操作符重载函数
class Type{ public: Type operator Sign(const Type& p) { Type ret; return ret; }};
这里再举一个例子:
#include <stdio.h>class Complex { int a; int b;public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } int getA() { return a; } int getB() { return b; } //虽然成员函数和友元都重载了操作符,但是系统会优先调用成员函数 Complex operator + (const Complex& p) { Complex ret; printf("Complex operator + (const Complex& p)\n"); ret.a = this->a + p.a; ret.b = this->b + p.b; return ret; } friend Complex operator + (const Complex& p1, const Complex& p2);};Complex operator + (const Complex& p1, const Complex& p2){ Complex ret; printf("Complex operator + (const Complex& p1, const Complex& p2)\n"); ret.a = p1.a + p2.a; ret.b = p1.b + p2.b; return ret;}int main(){ Complex c1(1, 2); Complex c2(3, 4); Complex c3 = c1 + c2; // c1.operator + (c2) printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB()); return 0;}
小结
- 操作符重载是C++的强大特性之一
- 操作符重载的本质是通过函数扩展操作符的功能
operator
关键字是实现操作符重载的关键- 操作符重载遵循相同的函数重载规则
- 全局函数和成员函数都可以实现对操作符的重载
阅读全文
0 0
- 20、不一样的C++系列--操作符重载
- 21、不一样的C++系列--数组操作符的重载
- 22、不一样的C++系列--函数调用操作符的重载
- 5、不一样的C++系列--函数重载
- C++【操作符重载】
- c++::操作符重载
- C++:操作符重载
- c++string类的操作符重载
- 1、不一样的C++系列--C到C++的升级
- 37、不一样的C++系列--C语言异常处理
- 操作符重载(C++)
- C++-重载操作符<< >> = + - * /
- c++_操作符重载
- C# 基础知识系列之 操作符重载
- 操作符的重载
- 操作符的重载
- 操作符的重载
- 操作符的重载
- _ftol2_sse 优化时所占时间最长,但是不知道这个是什么意思?该怎么优化
- java的反射机制
- HTML5 CSS控制Table内外边框、颜色、大小示例
- git学习笔记
- 151. Reverse Words in a String
- 20、不一样的C++系列--操作符重载
- 【C++】【LeetCode】38. Count and Say
- ifstream读取数据块例程
- 制作风格——百变幻灯片,完全DIY(高级教程)
- 【HDU2865】Birthday Toy-Burnside引理+数论+DP矩阵优化
- STM32-串口通信printf重定向
- nginx源码浅析--主流程
- 主流浏览器密码获取-WebBrowserPassView二次开发
- Android中使用Spinner来实现图标文字并存的二级联动