C++ explicit关键字,修饰构造函数,ctor

#include <iostream>

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

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

class Rectangle
{
public:
#ifdef Want_compiler_to_add__function_of_int_2_Rectangle
	Rectangle(const int w, const int h = 1)
		: width(w), height(h)
	{};
#else
	explicit Rectangle(const int w, const int h = 1)
		: width(w), height(h)
	{};
#endif // Want_compiler_to_add__function_of_int_2_Rectangle

	~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 b = 10;	// 这可以通过的原因是,调用了Rectangle的构造函数。编译器自动为int添加了转化为 Rectangle 的方法。但是有时候这不是我们想要的行为。
						// 显式的为构造函数添加 explicit 就可以杜绝这种编译器的自动行为。
						// 添加之后,该行就会报错。
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/alexYuin/p/11972809.html
今日推荐