首页 > 编程语言 > 详细

C++ class内类型重载,operator Type()

时间:2019-12-02 20:25:51      阅读:79      评论:0      收藏:0      [点我收藏+]
#include <iostream>

// operator Type() 类型操作符重载
// operator int()
// operator double()
// ...

//////////////////////////////////////////////////////////

class Rectangle
{
public:
	Rectangle(const int w, const int h)
		: width(w), height(h)
	{};

	~Rectangle() {};
	operator int(); // 重载 int() 之后,Rectangle就可以像一个int被使用。

public:
	int width;
	int height;
};


//////////////////////////////////////////////////////////

Rectangle::operator int()
{
	return width * height;
}


//////////////////////////////////////////////////////////

void 
printInt(const int v)
{
	std::cout << v+5 << std::endl;
}

int
main()
{
	Rectangle a(40, 10);

	int v1 = a;						// 400
	int v2 = 1 + a;					// 401
	int v3 = static_cast<int>(a);	// 400
	std::cout << a << std::endl;	// 输出 400
	printInt(a);					// 输出 405

	return 0;
}

  

C++ class内类型重载,operator Type()

原文:https://www.cnblogs.com/alexYuin/p/11972756.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!