我有 2 个文件:
/****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*(){}
,那么我会遇到很多编译器错误。
所以请告诉我什么是 operator T*(void)
以及它何时被调用?
最佳答案
关于您的问题
operator type ()
是所谓的转换运算符。如果需要转换为 type
,然后该运算符函数用于进行转换。
在您的示例中,cout 使用您的 operator T* ()
使用用户定义的隐式转换将 x1 对象转换为指针,然后由 ostream 输出(cout 属于 std::ostream 类)operator<<
这需要一个 void* 。
其他问题
为了帮助您解决其他问题,请将头文件名从 iostream.h
更改为至 iostream
.标准 C++ 不知道 iostream.h
.在 C++ 成为标准之前,这些文件就是这样调用的。此外,您使用的所有 C header ,如 math.h, stdio.h
在 C++ 中仍然有效,但它们是所谓的向后兼容头文件。例如,您应该包括 cmath
和 cstdio
反而。这会将所有不是 C 中的宏的名称放入 namespace std
.而不是使用 cout
, 你使用 std::cout
.其他标识符也是如此。
关于c++ - 什么是 "operator T*(void)"以及它何时被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/275169/