[英]static_cast on class with conversion operator
I have just come across this behaviour and I am having a hard time understanding why this wouldn't work. 我刚刚遇到这种行为,我很难理解为什么这不起作用。
enum class TestEnum
{
Foo,
Bar
};
class MyClass
{
public:
operator TestEnum()
{
return m_enum;
}
TestEnum m_enum = TestEnum::Foo;
}
MyClass theClass;
int enumValue = static_cast< int >( theClass ); // does not work, conversion operator not called
int enumValue = static_cast< int >( static_cast< TestEnum >( theClass ) ) // works as expected
I understand the compiler only allows 1 implicit conversion and here I think there is only one implicit conversion from MyClass to TestEnum and then an explicit conversion. 我理解编译器只允许1个隐式转换,在这里我认为只有一个从MyClass到TestEnum的隐式转换然后是显式转换。
It is true that one implicit conversion is allowed. 确实允许一个隐式转换。 However: 然而:
static_cast< int >( theClass )
This is a conversion of some non- int
class type to int
. 这是一些非int
类类型转换为int
。 This is not a conversion to some unspecified type first, and only then a conversion to int
. 这不是先转换为某些未指定的类型,而只是转换为int
。 This is one conversion. 这是一次转换。
Therefore, if there is one implicit conversion to int
, then this is allowed. 因此,如果有一个隐式转换为int
,则允许这样做。 But there isn't a single implicit conversion to int
that's available here. 但是这里没有一个隐式转换为int
。
静态强制转换操作符不仅仅是从类型转换为类型,无论如何应该在源类型和目标类型之间定义关系。可以看到myclass和testenum类型之间存在关系,因此,转换运算符定义了两者之间的相关性。调用了类型,并调用了定义整数类型和特技类型之间关系的转换运算符。但是我的类和int类型之间没有直接的关系,因此编译器看不到任何可用于转换的转换运算符类型,因此代码行不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.