場景:
1.看到WTL的CWindow源碼時會發現這樣的operator重載,仔細看會發現它並不是重載()操作符.
operator HWND() const throw() { return m_hWnd; }
如果重載()操作符,應該是,返回值HWND應該在operator的左邊,而且應該有兩個括號()
HWND operator ()() const throw() { return m_hWnd; }
函數原型:
operator Type()
測試代碼:
#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; }
71.2 71.2 71.200001