C++ 工会强制所有成员发起,而不是只有一个活跃成员?

C++ 工会强制所有成员发起,而不是只有一个活跃成员?,c++,c++11,unions,C++,C++11,Unions,我有以下代码(删除了一些不必要的细节): 标题: enum class TargetType : uint8 { NoTarget , Location , Actor }; class Target { public: Target(); Target(const FVector &inLocation); Target(const AActor *inTargetActor); // ... some methods h

我有以下代码(删除了一些不必要的细节):

标题:

enum class TargetType : uint8
{
    NoTarget
    , Location
    , Actor
};


class Target
{
public:

    Target();
    Target(const FVector &inLocation);
    Target(const AActor *inTargetActor);

    // ... some methods here

private:

    TargetType targetType;

    union
    {
        FVector location;
        TWeakObjectPtr<AActor> targetActor;
    };
};
当我试图编译此文件时,会出现以下错误:

error C4582: 'Target::location': constructor is not implicitly called
error C4582: 'Target::targetActor': constructor is not implicitly called
error C4582: 'Target::targetActor': constructor is not implicitly called
error C4582: 'Target::location': constructor is not implicitly called
编译器抱怨工会成员没有被发起。第一个构造函数抱怨两个成员都没有被初始化。另外两个抱怨没有启动成员,例如,如果我想使用
Target::location
,编译器希望我也启动
Target::targetActor


如果我不打算使用这两个成员,例如在第一个构造函数中,我真的必须启动这两个成员吗?对我来说这毫无意义,因为我不想在这种情况下使用数据?另外,当我想使用
Target::targetActor
作为活动成员时,为什么我必须启动
Target::location
?我在这里遗漏了什么?

如果你两者都需要,那为什么是联合而不是结构?谢谢你的回复!澄清一下,我不需要同时使用它们。这是一个4级警告,它说的是实话。:-)如果您不喜欢这些信息,只需禁用警告。如果可以的话,最好使用std::optional。@BoPersson非常感谢!禁用警告成功了!如果你两者都需要,那为什么是联合而不是结构呢?谢谢你的回复!澄清一下,我不需要同时使用它们。这是一个4级警告,它说的是实话。:-)如果您不喜欢这些信息,只需禁用警告。如果可以的话,最好使用std::optional。@BoPersson非常感谢!禁用警告成功了!
error C4582: 'Target::location': constructor is not implicitly called
error C4582: 'Target::targetActor': constructor is not implicitly called
error C4582: 'Target::targetActor': constructor is not implicitly called
error C4582: 'Target::location': constructor is not implicitly called