Go C + + implicit type conversion operator T
http://m.blog.csdn.net/blog/micx0124/12389973#
For the operator keyword for operator overloading we all know that operator has another role: coercion type conversion. Last week in order to correspond to a problem in the project, the colleague helped write a class, the use of operator forced type conversion, then source review when a few leader also do not understand its role, asked me how it happened, then I was just smattering, Helpless analysis of half a day also did not let leader understand, Khan ... It was then clear to the colleagues to parse it.
The following is an example to illustrate:
/*************************test_operatorconvert.h*************************/#ifndef Test_operatorconvert_h#define test_operatorconvert_hconst int max_path2 = 256;class test_operatorconvert{public: test_operatorconvert (); Test_operatorconvert (char *str); Virtual ~test_operatorconvert (); Char *getstr (); Operator char* ();p rivate: char m_sztest[max_path2];}; #endif
/*************************test_operatorconvert.cpp*************************/#include "stdafx.h" #include "Test_ OperatorConvert.h "#include <iostream>using namespace std; Test_operatorconvert::test_operatorconvert () { memset (m_sztest, 0, sizeof (m_sztest));} Test_operatorconvert::test_operatorconvert (char *str) { strcpy (m_sztest, str);} The function of Test_operatorconvert::~test_operatorconvert () {}//) is consistent with the function of operator char* (). Char *test_operatorconvert::getstr () { return m_sztest;} Test_operatorconvert::operator char* () { return m_sztest;}
int main (int argc, char* argv[]) { Test_operatorconvert ctestinstance; char *ptest1 = ctestinstance; This is where operator char* () works, //class Test_operatorconvert are converted to char* type. char *ptest2 = CTESTINSTANCE.GETSTR ();//If Operator char* () is not implemented, the same method is used. return 0;}
Some people call this method: implicit type conversion, the basic method of implementation is: operator type_name ();
C + + operator knowledge points