https://blog.csdn.net/infoworld/article/details/38901127
1、表达式格式
HWND operator ()() const throw() { return m_hWnd; }
与类型改变表达式格式区别:
operator HWND() const throw() { return m_hWnd; }
案例:
#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; }
2、调用方式:两种
先声明;再实例化;再调用,用对象调用operator();
#include <iostream> using namespace std; template<typename T> struct m_plus { T operator()(const T& x, const T& y) { return x + y; } }; int main(int argc, char *argv[]) { // 定义其对象 调用其operator() m_plus<int> op; cout << op(1, 2) << endl; // 产生一个匿名对象 这是仿函数的主流用法 cout << m_plus<int>()(1, 2) << endl; return 0; }