what is “operator T*(void)” and when it is invoked?

前端 未结 2 1351
既然无缘
既然无缘 2021-01-06 11:34

I have 2 files:

/****demo.cpp****/
#include 
#include \"gc.h\"

class foo{};

int main(){
    gc x1;
    cout<

        
2条回答
  •  一个人的身影
    2021-01-06 12:08

    Regarding your Question

    operator type () is a so-called cast operator. if there is a need for conversion to type, then that operator function is used to do the conversion.

    in your example, cout uses your operator T* () to convert your x1 object using a user defined implicit conversion to a pointer, which is then output by ostream's (cout is of class std::ostream) operator<< which takes a void* .

    Other Problems

    To help you figure out other problems, change the header file name from iostream.h to iostream . Standard C++ does not know iostream.h . Those files were called like that before C++ was made a Standard. Also, all C headers you use, like math.h, stdio.h are still valid in C++, but they are so-called backward-compatibility header files. You should include for example cmath and cstdio instead. That will put all names that are not macros in C into the namespace std. Instead of using cout , you use std::cout . Likewise for other identifiers too.

提交回复
热议问题