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

C++ 面向对象编程:关系运算符重载、函数调用运算符重载

对 ==、<、> 三个运算符分别进行重载,可见以下代码:

#include<iostream>
using namespace std;class location {
public:location(int x1, int y1) :x(x1), y(y1){};bool operator==(const location& l1) const{return x == l1.x && y == l1.y;}bool operator<(const location& l1) const {int a = x * x + y * y;int b = l1.x * l1.x + l1.y * l1.y;return a < b;}bool operator>(const location& l1) const {if (*this == l1) {return false;}if (*this < l1) {return false;}return true;}private:int x;int y;
};
int main() {location c(2, 3);location d(3, 4);if (c == d) {cout << "相等" << endl;}else if (c < d) {cout << "小于" << endl;}else {cout << "大于" << endl;}return 0;
}

函数调用运算符重载实现的函数叫做 “仿函数”,这里的话,功能是不变的,但是可以添加一些状态,就可以很灵活的加一些其他的操作,代码见下:

#include<iostream>
using namespace std;class test {public:test() {act = 0;}int operator()(int x, int y) {act++;return x + y + act;}
private:int act;
};
int main() {test testadd;cout << testadd(4, 5) << endl;//仿函数cout << testadd(4, 5) << endl;cout << testadd(4, 5) << endl;cout << testadd(4, 5) << endl;return 0;
}

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

相关文章:

  • 拉普拉斯分布极大似然估计
  • VLMs之Gemma 2:PaliGemma 2的简介、安装和使用方法、案例应用之详细攻略
  • qwenvl 代码中的attention pool 注意力池如何理解,attention pool注意力池是什么?
  • 源码分析之Openlayers中GeometryCollection类
  • 常见LLM大模型总结
  • 向量检索+大语言模型,免费搭建基于专属知识库的 RAG 智能助手
  • 基础11C++中的异常处理以及swap
  • 写作词汇积累:得偿所望、可见一斑、搭腔
  • android jetpack compose Model对象更新变量 UI不更新、不刷新问题
  • 数据库概论
  • 基于python使用UDP协议对飞秋进行通讯—DDOS
  • 数据库管理-第275期 Oracle 23ai:画了两张架构图(20241225)
  • 使用Streamlit部署机器学习模型
  • 依图科技简介
  • 苍穹外卖day07缓存部分分析
  • OCR实践-Table-Transformer
  • HarmonyOS NEXT 实战之元服务:静态案例效果---电台推荐
  • 微信小程序 不同角色进入不同页面、呈现不同底部导航栏
  • MATLAB符号计算-符号表达式基础运算操作
  • 服务器被攻击怎么办
  • 精准识别花生豆:基于EfficientNetB0的深度学习检测与分类项目
  • 【UE5 C++课程系列笔记】13——GameInstanceSubsystem的简单使用
  • 实用工具推荐----Doxygen使用方法
  • js垃圾回收机制详细讲解
  • 【Linux/踩坑】Linux中启动eclipse或HDFS因JAVA_HOME设置报错
  • 百度千帆平台构建AI APP的基础概念梳理
  • Unity3D Huatuo技术原理剖析详解
  • 记Fastjson2的一个报ConcurrentModificationException的bug
  • 使用TimesFM 对车辆销售进行预测
  • OpenEuler 22.03 不依赖zookeeper安装 kafka 3.3.2集群