标签:类型转换操作符 type conversion operator 中括号
场景:
1.看到WTL的CWindow源码时会发现这样的operator重载,仔细看会发现它并不是重载()操作符.
operator HWND() const throw()
{
return m_hWnd;
}如果重载()操作符,应该是,返回值HWND应该在operator的左边,而且应该有两个括号()
HWND operator ()() const throw()
{
return m_hWnd;
}
函数原型:
operator Type()
测试代码:
#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
[C/C++]_[操作符重载operator type()和operator()的区别]
标签:类型转换操作符 type conversion operator 中括号
原文地址:http://blog.csdn.net/infoworld/article/details/38901127