[c/c++]_[Operator overloading operator type () and operator ()]

Source: Internet
Author: User


Scene:

1. See WTL CWindow Source code will find such a operator overload, look closely will find it is not overloaded () operator.

operator HWND () const throw () {return m_hwnd;}

If the overloaded () operator, it should be, the return value HWND should be on the left side of operator, and should have 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, and if the conversion is defined, the benefit is that the class object is assigned a value of method (HWND), Parameter is a method of the HWND type that is automatically converted to the HWND type, or when the class information needs to be printed. Operator std::string ().


Function Prototypes:

Operator Type ()

The overloaded () operator does need to be called () before it is called, such as Object ([Param]).

Test code:

#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;co UT << (std::string) to << endl;//cout << to (0.9) << Endl;return 0;}

Output:

71.271.271.200001


[c/c++]_[Operator overloading operator type () and operator ()]

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.