[C/C ++] _ [operator reloads operator type () and operator ()]
Scenario:
1. When we see the CWindow source code of WTL, we will find this operator overload. If we look at it carefully, we will find that it is not an overloaded () operator.
operator HWND() const throw(){return m_hWnd;}
If the overload () operator is used, it should be that the returned value of HWND should be on the left side of the operator, and there should be two parentheses ()
HWND operator ()() const throw(){return m_hWnd;}
This type of operator overload should be type conversion operator (type conversion operator), which can convert the class type to the specified type. If this type of conversion is defined, the advantage is that the class object is assigned to method (HWND). If the parameter is an HWND type method, it is automatically converted to the HWND type, or the class information needs to be printed. Operator std: string ().
Function prototype:
operator Type()
The overload () operator must call (), for example, object ([param]).
Test code:
#include
#include
#include
#include
#include
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;}
Output:
71.271.271.200001