能否将类对象转换为 int、double、char 等。它是隐式转换还是显式转换?
class MyClass
{
int x;
};
int main()
{
MyClass MyObject; //convert my object to int
}
最佳答案
创建一个转换运算符:
class Foo {
public:
operator int() const { return 1; }
};
class Bar {
public:
operator Foo() const { return Foo(); }
};
int main() {
Foo f;
Bar b;
int i1 = f; // implicit, just one conversion
int i2 = b; // not valid
int i3 = static_cast<Foo>(b); // Convert b to Foo explicitly, Foo to int implicitly
}
关于c++ - 一个类对象到另一个数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5304606/