当前位置: 首页 > news >正文

QT学习(五)C++函数重载

一、 函数重载

在同一个作用域内,可以声明几个功能类似的同名函数,
这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。您不能仅通过返回类型的不同来 重载函数。
下面的实例中,同名函数 print() 被用于输出不同的数据类型
#include <iostream>
#include "string"
using namespace std;
class printData
{
public:void print(int i) {cout << "整数为: " << i << endl;}void print(double f) {cout << "浮点数为: " << f << endl;}void print(string str) {cout << "字符串为: " << str << endl;}
};
void print(int i) {cout << "整数为: " << i << endl;
}
void print(double f) {cout << "浮点数为: " << f << endl;
}
void print(string str) {cout << "字符串为: " << str << endl;
}void print(int i,double f) {cout << "整数为: " << i <<",浮点数为:"<<f<< endl;
}int main(void)
{print(5);print(500.13);print("hello world");print(1,23.2);printData pd;// 输出整数pd.print(5);// 输出浮点数pd.print(500.263);// 输出字符串string str = "Hello C++";pd.print(str);return 0;
}

二、 运算符重载

C++ 中,运算符重载是一个允许程序员自定义各种运算符(如 + , - , == , != 等)在自定义类型(类或结构体)上的行为的特性。这意味着你可以定义类似于内置类型的运算符行为,使你的自定义类型更加直观和易于使用。
基本原则
1. 不可以创建新的运算符 :只能重载已经存在的运算符。
2. 至少有一个操作数是用户定义的类型 :不能重载两个基本类型的运算符。
3. 不能更改运算符的优先级 :重载的运算符保持其原有的优先级和结合性。
示例 1 :假设我们有一个 Person 类,我们可以重载 == 运算符来实现两个 Person 是否相等的判断。
#include <iostream>
using namespace std;
class Person
{
public:string name;int inNumberTail;bool operator==(Person pTmp);
};bool Person::operator==(Person pTmp){return pTmp.name == name && pTmp.inNumberTail == inNumberTail;
}
int main()
{//假设我们认定名字和身份证尾号6位一样的两个对象是同一个人!Person p1;p1.name = "张三";p1.inNumberTail = 412508;Person p2;p2.name = "张三";p2.inNumberTail = 412508;bool ret = p1 == p2;cout << ret << endl;return 0;
}
示例 2 :假设我们有一个简单的 Point 类,我们可以重载 + 运算符来实现两个点的加法。
#include <iostream>
using namespace std;
class Point {
public:int x, y;// 重载 + 运算符Point operator+(Point other) {Point res;res.x = x + other.x;res.y = y + other.y;return res;}
};
int main() {Point p1;p1.x = 1;p1.y = 2;Point p2;p2.x = 2;p2.y = 3;Point p3 = p1 + p2; // 使用重载的 + 运算符std::cout << "p3.x: " << p3.x << ", p3.y: " << p3.y << std::endl; // 输出return 0;};

http://www.lryc.cn/news/298642.html

相关文章:

  • 微服务OAuth 2.1扩展额外信息到JWT并解析(Spring Security 6)
  • Python@setter用法介绍
  • 格子表单GRID-FORM | 文档网站搭建(VitePress)与部署(Github Pages)
  • mac无法往硬盘里存东西 Mac硬盘读不出来怎么办 Mac硬盘格式 硬盘检测工具
  • DataX源码分析 reader
  • openssl3.2 - exp - RAND_bytes_ex
  • Oracle中怎么设置时区和系统时间
  • 常见的物联网操作系统介绍
  • 二级C语言笔试10
  • 【WebSocket】微信小程序原生组件使用SocketTask 调用星火认知大模型
  • [1-docker-01]centos环境安装docker
  • 深度学习基础之《深度学习介绍》
  • 4核8g服务器能支持多少人访问?2024新版测评
  • Linux中pipe管道操作
  • 中年中产程序员从西安出发到海南三亚低成本吃喝万里行:西安-南宁-湛江-雷州-徐闻-博鳌-陵水-三亚-重庆-西安(2.游玩过程)
  • day38 面向对象编程、构造函数等(纯概念)
  • nginx用域名http://xx.com/aaa/代理一个网页http://ff.com但是请求资源时发生404
  • NLP_词的向量表示Word2Vec 和 Embedding
  • python:xml.etree 生成思维导图 Freemind文件
  • Solidworks:从2D走向3D
  • 【开源】JAVA+Vue.js实现高校学院网站
  • 题解19-24
  • 基于图像掩膜和深度学习的花生豆分拣(附源码)
  • 【网络】:序列化和反序列化
  • AJ-Report 【开源的一个BI平台】
  • Matplotlib核心:掌握Figure与Axes
  • 问题:A注册会计师必须在期中实施实质性程序的情形是()。 #学习方法#其他
  • C#系列-C#EF框架返回单行记录(24)
  • 【PyTorch】张量(Tensor)的生成
  • 【5G NR】【一文读懂系列】移动通讯中使用的信道编解码技术-Viterbi译码原理