【C++ 函数重载】

C++ 函数重载

  • ■ C++ 函数重载简介
  • ■ C++ 运算符重载
    • ■ 一元运算符重载
    • ■ 二元运算符重载 (+,-,*,/)
    • ■ 关系运算符重载 ( < 、 > 、 <= 、 >= 、 == 等等)
    • ■ 输入/输出运算符重载(运算符 >> 运算符 << )
    • ■ 赋值运算符重载( = )
    • ■ 函数调用运算符 () 重载
    • ■ 下标运算符 [] 重载
    • ■ 类成员访问运算符 -> 重载

■ C++ 函数重载简介

C++ 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载。
重载声明是指一个与之前已经在该作用域内声明过的函数具有相同名称的声明,但是它们的参数列表和定义(实现)不相同。
函数名相同,参数不同;

示例一:函数重载

#include <iostream>
using namespace std; 
class printData
{public:void print(int i) {cout << "整数为: " << i << endl;}void print(double  f) {cout << "浮点数为: " << f << endl;}void print(char c[]) {cout << "字符串为: " << c << endl;}
};int main(void)
{printData pd;// 输出整数pd.print(5);// 输出浮点数pd.print(500.263);// 输出字符串char c[] = "Hello C++";pd.print(c); return 0;
}
会产生下列结果:
整数为: 5
浮点数为: 500.263
字符串为: Hello C++

■ C++ 运算符重载

您可以重定义或重载大部分 C++ 内置的运算符。
函数名是由关键字 operator 和其后要重载的运算符符号构成的。
重载运算符有一个返回类型和一个参数列表。

Box operator+(const Box&);     //声明加法运算符用于把两个 Box 对象相加,返回最终的 Box 对象

■ 一元运算符重载

一元运算符只对一个操作数进行操作

示例一:

#include <iostream>
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 对象相加Box operator+(const Box& b){Box box;box.length = this->length + b.length;box.breadth = this->breadth + b.breadth;box.height = this->height + b.height;return box;}private:double length;      // 长度double breadth;     // 宽度double height;      // 高度
};
// 程序的主函数
int main( )
{Box Box1;                // 声明 Box1,类型为 BoxBox Box2;                // 声明 Box2,类型为 BoxBox Box3;                // 声明 Box3,类型为 Boxdouble volume = 0.0;     // 把体积存储在该变量中// Box1 详述Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0);// Box2 详述Box2.setLength(12.0); Box2.setBreadth(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;// 把两个对象相加,得到 Box3Box3 = Box1 + Box2;// Box3 的体积volume = Box3.getVolume();cout << "Volume of Box3 : " << volume <<endl;return 0;
}
它会产生下列结果:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

示例二:一元减运算符,即负号( - )

#include <iostream>
using namespace std;class Distance
{private:int feet;             // 0 到无穷int inches;           // 0 到 12public:// 所需的构造函数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);}
};
int main()
{Distance D1(11, 10), D2(-5, 11);-D1;                     // 取相反数D1.displayDistance();    // 距离 D1-D2;                     // 取相反数D2.displayDistance();    // 距离 D2return 0;
}
它会产生下列结果:
F: -11 I:-10
F: 5 I:-11

■ 二元运算符重载 (+,-,*,/)

二元运算符需要两个参数(+,-,*,/)

示例一:

   // 重载 + 运算符,用于把两个 Box 对象相加Box operator+(const Box& b){Box box;box.length = this->length + b.length;box.breadth = this->breadth + b.breadth;box.height = this->height + b.height;return box;}
函数使用:
// 把两个对象相加,得到 Box3
Box3 = Box1 + Box2;

■ 关系运算符重载 ( < 、 > 、 <= 、 >= 、 == 等等)

C++ 语言支持各种关系运算符( < 、 > 、 <= 、 >= 、 == 等等)

示例一:

#include <iostream>
using namespace std;class Distance
{private:int feet;             // 0 到无穷int inches;           // 0 到 12public:// 所需的构造函数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;}
};使用:
int main()
{Distance D1(11, 10), D2(5, 11);if( D1 < D2 ){cout << "D1 is less than D2 " << endl;}else{cout << "D2 is less than D1 " << endl;}return 0;
}
它会产生下列结果:
D2 is less than D1

■ 输入/输出运算符重载(运算符 >> 运算符 << )

C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。
您可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。
示例一:

#include <iostream>
using namespace std;class Distance
{private:int feet;             // 0 到无穷int inches;           // 0 到 12public:// 所需的构造函数Distance(){feet = 0;inches = 0;}Distance(int f, int i){feet = f;inches = i;}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;            }
};
int main()
{Distance D1(11, 10), D2(5, 11), D3;cout << "Enter the value of object : " << endl;cin >> D3;cout << "First Distance : " << D1 << endl;cout << "Second Distance :" << D2 << endl;cout << "Third Distance :" << D3 << endl;return 0;
}它会产生下列结果:
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10

■ 赋值运算符重载( = )

用于创建一个对象,比如拷贝构造函数。

示例一:

#include <iostream>
using namespace std; 
class Distance
{private:int feet;             // 0 到无穷int inches;           // 0 到 12public:// 所需的构造函数Distance(){feet = 0;inches = 0;}Distance(int f, int i){feet = f;inches = i;}void operator=(const Distance &D ){ feet = D.feet;inches = D.inches;}// 显示距离的方法void displayDistance(){cout << "F: " << feet <<  " I:" <<  inches << endl;}};
int main()
{Distance D1(11, 10), D2(5, 11);cout << "First Distance : "; D1.displayDistance();cout << "Second Distance :"; D2.displayDistance();// 使用赋值运算符D1 = D2;cout << "First Distance :"; D1.displayDistance();return 0;
}
它会产生下列结果:
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11

■ 函数调用运算符 () 重载

函数调用运算符 () 可以被重载用于类的对象。
当重载 () 时,您不是创造了一种新的调用函数的方式,相反地,这是创建一个可以传递任意数目参数的运算符函数。

示例一:

#include <iostream>
using namespace std;class Distance
{private:int feet;             // 0 到无穷int inches;           // 0 到 12public:// 所需的构造函数Distance(){feet = 0;inches = 0;}Distance(int f, int i){feet = f;inches = i;}// 重载函数调用运算符Distance operator()(int a, int b, int c){Distance D;// 进行随机计算D.feet = a + c + 10;D.inches = b + c + 100 ;return D;}// 显示距离的方法void displayDistance(){cout << "F: " << feet <<  " I:" <<  inches << endl;}      
};
int main()
{Distance D1(11, 10), D2;cout << "First Distance : "; D1.displayDistance();D2 = D1(10, 10, 10); // invoke operator()cout << "Second Distance :"; D2.displayDistance();return 0;
}
它会产生下列结果:
First Distance : F: 11 I:10
Second Distance :F: 30 I:120

■ 下标运算符 [] 重载

下标操作符 [] 通常用于访问数组元素。
重载该运算符用于增强操作 C++ 数组的功能。

示例一:

#include <iostream>
using namespace std;
const int SIZE = 10;class safearay
{private:int arr[SIZE];public:safearay() {register int i;for(i = 0; i < SIZE; i++){arr[i] = i;}}int& operator[](int i){if( i >= SIZE ){cout << "索引超过最大值" <<endl; // 返回第一个元素return arr[0];}return arr[i];}
};
int main()
{safearay A; cout << "A[2] 的值为 : " << A[2] <<endl;cout << "A[5] 的值为 : " << A[5]<<endl;cout << "A[12] 的值为 : " << A[12]<<endl;return 0;
}它会产生下列结果:
$ g++ -o test test.cpp
$ ./test 
A[2] 的值为 : 2
A[5] 的值为 : 5
A[12] 的值为 : 索引超过最大值
0

■ 类成员访问运算符 -> 重载

类成员访问运算符( -> )可以被重载,但它较为麻烦。
它被定义用于为一个类赋予"指针"行为。运算符 -> 必须是一个成员函数。
如果使用了 -> 运算符,返回类型必须是指针或者是类的对象。

运算符 -> 通常与指针引用运算符 * 结合使用,用于实现"智能指
示例一:

#include <iostream>
#include <vector>
using namespace std;// 假设一个实际的类
class Obj {static int i, j;
public:void f() const { cout << i++ << endl; }void g() const { cout << j++ << endl; }
};// 静态成员定义
int Obj::i = 10;
int Obj::j = 12;// 为上面的类实现一个容器
class ObjContainer {vector<Obj*> a;
public:void add(Obj* obj){ a.push_back(obj);  // 调用向量的标准方法}friend class SmartPointer;
};// 实现智能指针,用于访问类 Obj 的成员
class SmartPointer {ObjContainer oc;int index;
public:SmartPointer(ObjContainer& objc){ oc = objc;index = 0;}// 返回值表示列表结束bool operator++() // 前缀版本{ if(index >= oc.a.size() - 1) return false;if(oc.a[++index] == 0) return false;return true;}bool operator++(int) // 后缀版本{ return operator++();}// 重载运算符 ->Obj* operator->() const {if(!oc.a[index]){cout << "Zero value";return (Obj*)0;}return oc.a[index];}
};int main() {const int sz = 10;Obj o[sz];ObjContainer oc;for(int i = 0; i < sz; i++){oc.add(&o[i]);}SmartPointer sp(oc); // 创建一个迭代器do {sp->f(); // 智能指针调用sp->g();} while(sp++);return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:10
12
11
13
12
14
13
15
14
16
15
17
16
18
17
19
18
20
19
21

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/714257.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【嵌入式学习】网络编程day03.02

一、项目 1、TCP机械臂测试 #include <myhead.h> #define SER_IP "192.168.126.32" #define SER_PORT 8888 #define CER_IP "192.168.126.42" #define CER_PORT 9891 int main(int argc, const char *argv[]) {int wfd-1;//创建套接字if((wfdsocke…

ubuntu创建账号和samba共享目录

新建用于登录Ubuntu图形界面的用户 sudo su #切换为root用户获取管理员权限用于新建用户 adduser username #新建用户&#xff08;例如用户名为username&#xff09; adduser username sudo #将用户添加到 sudo 组 新建只能用于命令行下登录的用户 sudo su #切换为root用户…

《TCP/IP详解 卷一》第8章 ICMPv4 和 ICMPv6

目录 8.1 引言 8.1.1 在IPv4和IPv6中的封装 8.2 ICMP 报文 8.2.1 ICMPv4 报文 8.2.2 ICMPv6 报文 8.2.3 处理ICMP报文 8.3 ICMP差错报文 8.3.1 扩展的ICMP和多部报文 8.3.2 目的不可达和数据包太大 8.3.3 重定向 8.3.4 ICMP 超时 8.3.5 参数问题 8.4 ICMP查询/信息…

划分开始结束位置设置标记

划分开始结束位置 初始音轨如下图所示 在想开始地方单击左键&#xff0c;长按直到你想要的结束位置松开。就可以划分开始和结束位置 设置标记 方式1 &#xff1a;直接点击该图标 方式二&#xff1a;使用快捷键M 设置标记点可以自定义名称方便检索标记点

javaWebssh酒店客房管理系统myeclipse开发mysql数据库MVC模式java编程计算机网页设计

一、源码特点 java ssh酒店客房管理系统是一套完善的web设计系统&#xff08;系统采用ssh框架进行设计开发&#xff09;&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为TOMCAT7.0…

STL容器之string类

文章目录 STL容器之string类1、 什么是STL2、STL的六大组件3、string类3.1、string类介绍3.2、string类的常用接口说明3.2.1、string类对象的常见构造3.2.2、string类对象的容量操作3.2.3、string类对象的访问及遍历操作3.2.4、 string类对象的修改操作3.2.5、 string类非成员函…

车辆维护和燃油里程跟踪器LubeLogger

什么是 LubeLogger &#xff1f; LubeLogger 是一个自托管、开源、基于网络的车辆维护和燃油里程跟踪器。 LubeLogger 比较适合用来跟踪管理您的汽车的维修、保养、加油的历史记录&#xff0c;比用 Excel 强多了 官方提供了在线试用&#xff0c;可以使用用户名 test 和密码 123…

oracle-long类型转clob类型及clob类型字段的导出导入

1、若oracle数据库表字段类型有long类型&#xff0c;有时候我们需要模糊匹配long类型字段时&#xff0c;是查询不出来结果的&#xff0c;此时使用TO_LOB&#xff0c;将long类型转成clob类型&#xff0c;就可以模糊匹配信息。 例如&#xff1a;oracle数据库查询所有视图内容中包…

机器学习-4

文章目录 前言数组创建切片索引索引遍历切片编程练习 总结 前言 本篇将介绍数据处理 Numpy 库的一些基本使用技巧&#xff0c;主要内容包括 Numpy 数组的创建、切片与索引、基本运算、堆叠等等。 数组创建 在 Python 中创建数组有许多的方法&#xff0c;这里我们使用 Numpy 中…

机器学习-5

文章目录 前言Numpy库四则运算编程练习 前言 本片将介绍Numpy库中的四则运算。 Numpy库四则运算 Numpy库可以直接进行一些四则运算&#xff0c;快速的处理两个Numpy数组&#xff1a; a np.array([[1,2,3],[4,5,6]]) b np.array([[4,5,6],[1,2,3]])向量与向量之间 1.加法 …

14.最长公共前缀

题目&#xff1a;编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀&#xff0c;返回空字符串""。 解题思路&#xff1a;横向扫描&#xff0c;依次遍历每个字符串&#xff0c;更新最长公共前缀。另一种方法是纵向扫描。纵向扫描时&#xff0c;从前…

基于tomcat的JavaWeb实现

Tomcat服务器 免费&#xff0c;性能一般的服务器 安装配置 基于Java&#xff0c;故需要配置环境变量&#xff0c;新加系统路径JAVA_HOME&#xff0c;路径为jdk的主目录。 而后打开bin目录下的startup.bat文件出现如下窗口说明配置成功 idea继承tomcat服务器 使用java开发…

Linux 之压缩与解压相关命令的基础用法

目录 1、zip 与 unzip 2、gzip 命令 3、tar 命令 1、zip 与 unzip 在桌面新建一个文件和文件夹用于测试 在 test 目录下有一个 1.txt 文件 我们使用 zip 命令对其压缩 用法&#xff1a; zip 自定义压缩包名 被压缩文件路径位置 zip myon.zip 1.txt 因为我们这里就是在 …

linux_day04

大纲&#xff1a;命令&#xff0c;vim&#xff0c;gcc&#xff0c;编译工具&#xff0c;生成代码&#xff0c;调试&#xff0c;库makefile&#xff0c;系统编程 文件系统&#xff1a;文件属性&#xff0c;文件内容&#xff0c;万物皆文件&#xff08;不在内存中的是文件&#…

ProtoBuf 是什么?

1. 序列化概念 序列化和反序列化 序列化&#xff1a;把对象转换为字节序列的过程称为对象的序列化。 反序列化&#xff1a;把字节序列恢复为对象的过程称为对象的反序列化。 什么情况下需要序列化 存储数据&#xff1a;当你想把的内存中的对象状态保存到⼀个⽂件中或者存到数…

怎么压缩成mp4视频?

在数字化时代&#xff0c;视频已经成为我们日常生活中不可或缺的一部分。然而&#xff0c;有时候我们可能会遇到视频文件太大的问题&#xff0c;不便于传输、存储或分享。那么&#xff0c;如何将视频压缩成MP4格式&#xff0c;以减小文件大小呢&#xff1f;本文将为您介绍几种简…

docker学习第一步:基于Linux安装docker!

要求Linux下的CentOS 7.0 以上的版本 01、安装docker版本仓库 1、设置仓库 sudo yum install -y yum-utils device-mapper-persistent-data lvm2 2、稳定仓库 sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo 现在我也找了很…

医学大数据|文献阅读|有关“胃癌+机器学习”的研究记录

目录 1.基于32基因特征构建的机器学习模型可有效预测胃癌患者的预后和治疗反应 2.胃癌患者术后90天死亡率的机器学习风险预测模型 3.使用机器学习模型预测幽门螺杆菌根除患者胃癌患病风险 4.利用初始内窥镜检查和组织学结果进行个性化胃癌发病率预测 1.基于32基因特征构建的…

随想录算法训练营第四十八天|121. 买卖股票的最佳时机、122.买卖股票的最佳时机II

121. 买卖股票的最佳时机 public class Solution {public int MaxProfit(int[] prices) {int result0;int lowint.MaxValue;for(int i0;i<prices.Length;i){if(prices[i]<low){lowprices[i];}else{resultMath.Max(result,prices[i]-low);}}return result;} } 先遍历找到…

机器学习_10、集成学习-AdaBoost

AdaBoost AdaBoost&#xff08;Adaptive Boosting的简称&#xff09;是一种集成学习方法&#xff0c;它的核心思想在于将多个弱学习器组合起来&#xff0c;形成一个强学习器。通过这种方式&#xff0c;AdaBoost能够显著提高分类性能。下面详细介绍AdaBoost的主要概念和工作原理…