Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

c++ - What is an "operator int" function?

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++;
   }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...