【问题标题】:C++ Cast operator overload [duplicate]C ++ Cast运算符重载[重复]
【发布时间】:2020-02-22 19:25:49
【问题描述】:

我有一个只有一个 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 个。

【问题讨论】:

  • 问题是什么?

标签: c++ types casting typecasting-operator


【解决方案1】:

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

【讨论】:

  • 非常感谢!如果我在定义中将 int 更改为 float,它会自动将其转换为 float 吗?
  • @darkstylazz 在这种情况下,它将支持隐式转换为 float。当然,这种演员阵容是否真的会发生取决于用例。
猜你喜欢
  • 2012-02-06
  • 2011-10-27
  • 2012-12-22
  • 2016-09-26
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-29
相关资源
最近更新 更多