什么是“操作符T *(void)”。和什么时候调用? [英] what is "operator T*(void)" and when it is invoked?

查看:235
本文介绍了什么是“操作符T *(void)”。和什么时候调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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告诉我什么是 关于您的问题

解决方案

运算符类型()是所谓的cast运算符。如果需要转换为类型,则使用该运算符函数进行转换。



在您的示例中,cout使用您的运算符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 。对于其他标识符也是如此。


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?

解决方案

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.

这篇关于什么是“操作符T *(void)”。和什么时候调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆