What is an “operator int” function?

前端 未结 5 1078
南旧
南旧 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 03:12

    First things first:

    $12.3.1/1 - "A constructor declared without the function-specifier explicit specifies a conversion from the types of its parameters to the type of its class. Such a constructor is called a converting constructor."

    In your example, INT is a User Defined class that has a converting constructor from 'int'.

    Therefore the following code is well-formed:

    INT i(1024);     // direct initialization syntax
    

    This means that you can get an INT object from an integer. However what does one do, if the INT object has to be converted back to an integer? Transitivity?

    One can say that the class INT can provide a member function to return the encapsulated integer member

    int x = i.geta();
    

    This however is not very intuitive and is not a standardized approach. Also it is not intuitive when it comes to how built-in types work in such situations.

    int z = 0;
    int y1 = z; // copy initialization or
    int y2(z);  // direct initialization
    double d = (int )z; // explicit cast
    

    Therefor the Standard allows for such standardization and intuitiveness of converting User Defined Types by saying:

    $12.3/2 - "A member function of a class X having no parameters with a name of the form [...]

    operator conversion-type-id

    [...]specifies a conversion from X to the type specified by the conversion-type-id. Such functions are called conversion functions. No return type can be specified. If a conversion function is a member function, the type of the conversion function (8.3.5) is “function taking no parameter returning conversion-type-id”.

    This makes all of the following well-formed and retains harmony with the way built-in types work is

    int y1 = i; // copy initialization or
    int y2(i);  // direct initialization
    double d = (int )i; // explicit cast
    

提交回复
热议问题