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

  

相关文章:

  • 2021-09-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-16
  • 2022-02-11
  • 2021-07-12
  • 2021-12-25
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-17
  • 2021-06-13
  • 2021-05-15
  • 2021-06-06
  • 2021-05-27
相关资源
相似解决方案