C++中的函数重载
来源:互联网 发布:淘宝店提前收款 编辑:程序博客网 时间:2024/06/06 17:28
C++ 中的运算符重载
你可以重新定义或重载的大部分 C++ 已有的操作符。因此,程序员可以像使用用户自定义类型一样使用操作符。
重载操作符是一类函数,它们就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。像任何其它函数,重载运算符也有返回类型和参数列表。
Box operator+(const Box&);
声明加法运算符可以用来使两个 Box 对象相加并返回最终 Box 对象。大多数重载运算符可以被定义为普通非成员函数或类成员函数。如果我们把上面的函数定义为一个类的非成员函数,那么我们就必须为每个操作数传两个参数如下:
Box operator+(const Box&, const Box&);
下面是通过使用成员函数来展示运算符重载的概念的示例。这里一个对象作为一个参数被传递,通过访问这个对象可以获得参数的属性,将调用这个操作符的对象可以通过使用 this 操作符获得,下面这个例子展示了这一点:
#include<bits/stdc++.h>using namespace std;class Box{ public : double getVolume(void) { return length * breadth * height; } void setLength(double len) { length = len; } void setBreadth(double bre) { breadth = bre; } void setHeight( double hei ) { height = hei; } Box operator + (const Box &other)//第一种重载方式 { Box box; box.length = this->length + other.length; box.breadth = this->breadth + other.breadth; box.height = this->height + other.height; return box; } public: double length; double breadth; double height;};Box operator + (const Box &ths, const Box &other)//第二种重载方式{ Box box; box.length = ths.length + other.length; box.breadth = ths.breadth + other.breadth; box.height = ths.height + other.height; return box;}int main(){ Box Box1, Box2, Box3; double volume = 0; Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; // Add two object as follows: Box3 = Box1 + Box2; // volume of box 3 volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0;}
上面的代码编译和执行时,它产生以下结果:
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400
可重载/不可重载的运算符
下面这张表列举了可以重载的运算符:
+-*/%^&|~!,=<><=>=++--<<>>==!=&&||+=-=/=%=^=&=|=*=<<=>>=[ ]()->->*newnew[ ]deletedelete[ ]下面这张表列举了不可以重载的运算符:
::.*.?:运算符重载例子
这里有各种操作符重载的例子来帮助你理解这一概念。
0 0
- C++中的函数重载
- C#中的函数重载
- C#中的函数重载
- C++中的函数重载
- C++中的函数重载
- C++中的函数重载
- C++中的函数重载
- c++中的函数重载
- C++中的函数重载
- C++中的函数重载
- JavaScript 中的函数重载
- 类中的函数重载
- C/C++ 函数重载
- [c++]函数重载
- C++:函数重载
- Objective-C函数重载
- c++-函数重载
- C++-函数重载
- RecyclerView使用攻略(刷新篇)
- mybatis学习笔记-实现查询用户信息功能
- Tensorflow学习精要版IV ---- 开始稍微深入了解一下
- 面试题9:菲波那切数列
- IO流_随机获取文本文件中的姓名案例
- C++中的函数重载
- 创建maven项目
- 深度纹理编码网络 (Deep TEN: Texture Encoding Network)
- 霍夫曼树之切割木板最小总代价问题
- 微信小程序使用WebService(Asp.net)进行数据交互
- XML学习总结
- 一道求极值的三角函数题
- Markdown笔记
- Scala基础语法-3Map