#include "gc.h" class foo{...">

What is the "T * (void) operator" and when is it called?

I have 2 files:

/****demo.cpp****/
#include <iostream.h>
#include "gc.h"

class foo{};

int main(){
    gc<foo> x1;
    cout<<x1;
}

/*****gc.h*****/
template <class T> class gc 
{
    T* ptr;
public:
    operator T*(){}
};

If I do not write operator T*(){}, then I get a lot of compiler errors.

So plz tell me what is it operator T*(void)and when is it called?

+3
source share
2 answers

Regarding your question

operator type ()- This is the so-called casting operator. if there is a need to convert to type, then this operator function is used to convert to.

in your example, cout uses yours operator T* ()to convert your x1 object using an implicit conversion of the user to a pointer, which is then output via ostream (cout has the class std :: ostream) operator<<, which accepts void *.

Other problems

, iostream.h iostream. ++ iostream.h. , , ++ . , C , , math.h, stdio.h, ++, . , , cmath cstdio. , C, namespace std. cout std::cout. .

+3

T*(){} - . , gc<T> T*... , -, ptr.

, , gc .

gc foo *, ... , , .

, < < :

template <class T>
std::ostream& operator<<( std::ostream& os, const gc<T>& x)
{
    // os << .. something useful here ..
    return os;
}
+2

Source: https://habr.com/ru/post/1699320/


All Articles