C++ 强制转换运算符重载

dar*_*azz 7 c++ types casting typecasting-operator

我有一个只有一个 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;
   }
};
Run Code Online (Sandbox Code Playgroud)

因此,当我调用int()强制转换运算符时,我会返回data如下内容:

int main() {
 NewInt A(10);
 cout << int(A);
} 
Run Code Online (Sandbox Code Playgroud)

我会打印出10张。

Mat*_*ias 8

用户定义的强制转换或转换运算符具有以下语法:

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

代码[编译器资源管理器]:

#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;
} 
Run Code Online (Sandbox Code Playgroud)