C++重载 强制类型转换运算符

文章目录

1.函数调用运算符重载

c++ 复制代码
class Display
{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}

};
class Add
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};

int main() 
{
	Display Print;
	Print("hello world");

	Add add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

	//匿名对象调用  
	cout << "Add()(100,100) = " << Add()(100, 100) << endl;
	return 0;
}

2.强制类型转换运算符重载

2.1对运算符的认识

C++ 中类型的名字/类的名字本身是一种类型强制转换运算符

2.2类型强制转换运算符

  1. 单目运算符
  2. 可以被重载为成员函数[不能被重载为全局函数]

重载 int 类型强制转换运算符

c 复制代码
class Test
{
public:
	Test(int a = 0, int b = 0) 
		:_a(a)
		, _b(b) 
	{

	}
	//重载 强制类型转换运算符时 
	// 返回值类型是确定的 
	// 即运算符本身代表的类型
	// 不需要指定返回值类型
	operator int()
	{ 
		return _a; 
	}
private:
	int _a;
	int _b;
};
int main()
{
	Test obj(10, 20);
	//obj.operator int()
	cout << (int)obj << endl;  //10

	//类A如果对int进行了  强制类型转换运算符重载
	//那么类A的对象参与含int这个类型的表达式时 
	//该类A的对象就会调用operator int() 
	// 即类A的对象一旦出现在含int这个类型的表达式时
	// 这个对象在此处的值就是调用operator int()这个函数的返回值

	int n = 5 + obj;           //int n = 5 + obj.operator int()
	cout << n << endl;         //15
}
相关推荐
冷雨夜中漫步10 分钟前
Claude Code源码分析——Claude Code Agent Loop 详细设计文档
java·开发语言·人工智能·ai
麦兜和小可的舅舅10 分钟前
ClickHouse 列管理机制解析:从 COW、IColumn 到 CRTP
c++·clickhouse
超龄编码人12 分钟前
Qt Widgets Designer QTabWidget无法添加布局
开发语言·qt
北顾笙98013 分钟前
day38-数据结构力扣
数据结构·算法·leetcode
m0_6294947314 分钟前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
直奔標竿15 分钟前
Java开发者AI转型第二十六课!Spring AI 个人知识库实战(五)——联网搜索增强实战
java·开发语言·人工智能·spring boot·后端·spring
xin_nai18 分钟前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
Python大数据分析@21 分钟前
CLI一键采集,使用Python搭建TikTok电商爬虫Agent
开发语言·爬虫·python
旖-旎28 分钟前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
vegetablesssss29 分钟前
vtk镜像图
c++·qt·vtk