[C/C++]_[操作符重载operator type()和operator()的区别]


场景:

1.看到WTL的CWindow源码时会发现这样的operator重载,仔细看会发现它并不是重载()操作符.

	operator HWND() const throw()
	{
		return m_hWnd;
	}

如果重载()操作符,应该是,返回值HWND应该在operator的左边,而且应该有两个括号()

HWND operator ()() const throw()
{
	return m_hWnd;
}

这种类型的操作符重载应该是type conversion operator(类型转换操作符),它可以把类类型转换为指定的类型,如果定义了这种转换,好处就是该类对象赋值给 method(HWND),参数是HWND类型的方法时会自动转换为HWND类型,或者需要打印这个类信息时。operator std::string().


函数原型:

operator Type()

而重载()操作符确实是需要调用()才会调用,比如object([param])。

测试代码:

#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

class Total
{
public:
	Total(float sum,float discount)
	{
		sum_ = sum;
		discount_ = discount;
	}
	~Total(){}

	operator float()
	{
		return sum_* discount_;
	}

	operator std::string()
	{
		char str[128];
		sprintf(str,"%f",sum_* discount_);
		return std::string(str);
	}

	float operator()()
	{
		return sum_* discount_;
	}
	float sum_;
	float discount_;
};

int main(int argc, char const *argv[])
{
	Total to(89,0.8);
	cout << to << endl;
	cout << to() << endl;
	cout << (std::string)to << endl;
	//cout << to(0.9) << endl;
	return 0;
}


输出:

71.2
71.2
71.200001


你可能感兴趣的:(type,conversion,operator,中括号,类型转换操作符)