C++ Cast 运算符重载

C++ Cast operator overload

我有一个 class,只有一个 int 成员,例如:

class NewInt {
   int data;
public:
   NewInt(int val=0) { //constructor
     data = val;
   }
   int operator int(NewInt toCast) { //This is my faulty definition
     return toCast.data;
   }
};

因此,当我调用 int() 转换运算符时,我会 return data 例如:

int main() {
 NewInt A(10);
 cout << int(A);
} 

我会打印 10 个。

A user-defined cast or conversion operator 具有以下语法:

  • operator conversion-type-id
  • explicit operator conversion-type-id (C++11 起)
  • explicit ( expression ) operator conversion-type-id (C++20 起)

代码 [Compiler Explorer]:

#include <iostream>

class NewInt
{
   int data;

public:

   NewInt(int val=0)
   {
     data = val;
   }

   // Note that conversion-type-id "int" is the implied return type.
   // Returns by value so "const" is a better fit in this case.
   operator int() const
   {
     return data;
   }
};

int main()
{
    NewInt A(10);
    std::cout << int(A);
    return 0;
}