简体   繁体   中英

Forward declared enum, default value in .h

Types.h :

enum MyEnum : int8
{
    invalid = -1,
    valid = 0,
}

class TestClass 
{ ... default stuff ...}

MyOtherHeader.h :

enum MyEnum : int8;
class TestClass;

class MyClass
{
    MyEnum Val = -1;
    TestClass* MyObj= nullptr;
}

Why can we assign null to a forward declare Class Pointer, but can't assign a value of the defined underlying type of the enum to a forwarded declared one?

Shouldn't the compiler be able to "deduce" that properly?

TLDR : The question is : Why do we need a work around to assign a default value to the forward declared enum property?

There is no implicit conversion from an int to an enumeration. As such, you can't copy-initialize (use = ) an enum from an int. So even this

enum MyEnum : int8
{
    invalid = -1,
    valid = 0,
};

MyEnum e = -1;

Would produce the same error. You can either add a cast, or switch to direct-initialization (which a cast is also a form of, here):

MyEnum e{-1};

The above direct-initializes the variable, though sadly only since C++17. In our particular case you could use it to provide a default member initializer for your member if you can use a C++17 capable compiler. Otherwise, casting is the only way to provide an initializer for an enumeration from an integer.

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