C++类型转换运算符重载

7

我有一个只有一个 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()强制类型转换运算符时,将返回data,如下所示:

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

我要印10份纸质版。


什么是问题? - Petok Lorand
1个回答

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;
} 

非常感谢!如果我在定义中将int更改为float,它会自动转换为float吗? - darkstylazz
@darkstylazz在这种情况下,它将支持对float的隐式转换。当然,这样的转换是否实际发生取决于使用情况。 - Matthias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接