What is an “operator int” function?

前端 未结 5 1082
南旧
南旧 2020-12-08 02:10

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

class INT
{
   int a;

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

   /* Starting here:         


        
5条回答
  •  心在旅途
    2020-12-08 02:58

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

    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.

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

    INT i(1234);
    int i_2 = i; // this will implicitly call INT::operator 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
    

提交回复
热议问题