Reputation:
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 don't write operator T*(){}
then I get a lot of compiler errors.
So plz tell me what is operator T*(void)
and when it is invoked?
Upvotes: 3
Views: 1184
Reputation: 507095
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* .
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.
Upvotes: 3
Reputation: 47472
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;
}
Upvotes: 2