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

前端 未结 2 1345
既然无缘
既然无缘 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.

    0 讨论(0)
  • 2021-01-06 12:11

    operator T*(){} is a cast operator. You are providing a function that can be used to convert from a gc<T> to a T* ... though it should require that you actually return something, presumably ptr in this case.

    The problem is that the compiler doesn't know how to format your gc object to the output stream.

    By providing a cast from gc to foo* it is able to output the object as just a pointer value ... probably not what you want.

    You likely want to define a custom overload for the << operator to dump out your class:

    template <class T>
    std::ostream& operator<<( std::ostream& os, const gc<T>& x)
    {
        // os << .. something useful here ..
        return os;
    }
    
    0 讨论(0)
提交回复
热议问题