什么是“操作符T *(void)”。和什么时候调用? [英] what is "operator T*(void)" and when it is invoked?
问题描述
我有2个档案:
/ **** demo.cpp **** /
# include< iostream.h>
#includegc.h
class foo {};
int main(){
gc< foo> x1;
cout<< x1;
}
/*****gc.h*****/
template< class T> class gc
{
T * ptr;
public:
operator T *(){}
};
如果我不写 code>然后我得到了很多编译器错误。
所以plz告诉我什么是 在您的示例中,cout使用您的 要帮助您找出其他问题,请更改头文件名从 I have 2 files: If I don't write So plz tell me what is in your example, cout uses your To help you figure out other problems, change the header file name from 这篇关于什么是“操作符T *(void)”。和什么时候调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 关于您的问题
解决方案 运算符类型()
是所谓的cast运算符。如果需要转换为类型
,则使用该运算符函数进行转换。
运算符T *()
转换为指针,然后通过ostream的(cout是类std :: ostream)运算符<
输出,它接受一个void *。
其他问题
iostream.h
到 iostream
。标准C ++不知道 iostream.h
。这些文件被称为像C ++之前做的标准。此外,您使用的所有C头文件,例如 math.h,stdio.h
在C ++中仍然有效,但它们是所谓的向后兼容头文件。您应该包括例如 cmath
和 cstdio
。这将把所有不是C中的宏的名字放在命名空间std
中。而不是使用 cout
,您使用 std :: cout
。对于其他标识符也是如此。/****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*(){}
};
operator T*(){}
then I get a lot of compiler errors.operator T*(void)
and when it is invoked?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. 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
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.