什么是“ operator int”?功能? [英] What is an "operator int" function?

查看:159
本文介绍了什么是“ operator int”?功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的 operator int函数是什么?

What is the "operator int" function below? What does it do?

class INT
{
   int a;

public:
   INT(int ix = 0)
   {
      a = ix;
   }

   /* Starting here: */
   operator int()
   {
      return a;
   }
   /* End */

   INT operator ++(int)
   {
      return a++;
   }
};


推荐答案

粗体代码是转换运算符。 (又名广播运营商

The bolded code is a conversion operator. (AKA cast operator)

它为您提供了一种方法,可以将您的自定义 INT 类型转换为另一种类型(在这种情况下, int ),而不必显式调用特殊的转换函数。

It gives you a way to convert from your custom INT type to another type (in this case, int) without having to call a special conversion function explicitly.

例如,使用convert运算符,此代码将编译:

For example, with the convert operator, this code will compile:

INT i(1234);
int i_2 = i; // this will implicitly call INT::operator int()

如果没有convert运算符,则上面的代码将无法编译,您必须做其他事情才能将 INT 转换为 int

Without the convert operator, the above code won't compile, and you would have to do something else to go from an INT to an int, such as:

INT i(1234);
int i_2 = i.a;  // this wont compile because a is private

这篇关于什么是“ operator int”?功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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