[C/C ++] _ [operator reloads operator type () and operator ()]

Source: Internet
Author: User

[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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.