我有一个只有一个 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张。
A 用户定义的强制转换或转换运算符 https://en.cppreference.com/w/cpp/language/cast_operator具有以下语法:
operator conversion-type-id
-
explicit operator conversion-type-id
(自 C++11 起)
-
explicit ( expression ) operator conversion-type-id
(自 C++20 起)
Code [编译器资源管理器 https://godbolt.org/z/FXoZAk]:
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)