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

#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;
}

  

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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/306860

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午4:47
下一篇 2023年2月16日 上午4:48

相关推荐