简体   繁体   中英

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.

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 . This is not a conversion to some unspecified type first, and only then a conversion to int . This is one conversion.

Therefore, if there is one implicit conversion to int , then this is allowed. But there isn't a single implicit conversion to int that's available here.

静态强制转换操作符不仅仅是从类型转换为类型,无论如何应该在源类型和目标类型之间定义关系。可以看到myclass和testenum类型之间存在关系,因此,转换运算符定义了两者之间的相关性。调用了类型,并调用了定义整数类型和特技类型之间关系的转换运算符。但是我的类和int类型之间没有直接的关系,因此编译器看不到任何可用于转换的转换运算符类型,因此代码行不起作用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM