C++Cast运算符过载

C++ Cast operator overload

本文关键字:运算符 C++Cast      更新时间:2023-10-16

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

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

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