AActor *UactorComponent::GetOwner const - 不允许指向不完整 class 类型的指针

AActor *UactorComponent::GetOwner const - pointer to incomplete class type is not allowed

我是 UE4 开发的新手,我已经学习了 Udemy 的 Unreal Engine 开发课程。我在 Actor 上创建了一个新组件,名为 PositionReporter header PositionReporter.h

#pragma once

#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "PositionReporter.generated.h"


UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class BUILDINGESCAPE_API UPositionReporter : public UActorComponent
{
    GENERATED_BODY()

public: 
    // Sets default values for this component's properties
    UPositionReporter();

protected:
    // Called when the game starts
    virtual void BeginPlay() override;

public: 
    // Called every frame
    virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
};

PositionReporter.cpp 中的代码为

#include "PositionReporter.h"

// Sets default values for this component's properties
UPositionReporter::UPositionReporter()
{
    // Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
    // off to improve performance if you don't need them.
    PrimaryComponentTick.bCanEverTick = true;

    // ...
}


// Called when the game starts
void UPositionReporter::BeginPlay()
{
    Super::BeginPlay();

    FString t = GetOwner()->GetActorLabel();

    UE_LOG(LogTemp, Warning, TEXT("Position Reporter reporting for duty on %s"), *t);

}


// Called every frame
void UPositionReporter::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    // ...
}

如您所见,我现在正尝试在指向通过 GetObject() 检索到的 AActor 的指针上调用 GetName 函数。

但是,当我输入 "GetObject()->" 时,不会弹出自动完成(就像在视频中那样),当我手动添加 "GetName()" 时,我会收到编译器错误 "pointer to incomplete class type is not allowed" .

哪里做错了?我是否缺少进口商品?我已经将我的代码与 Ben 的 git 存储库进行了比较,但没有发现任何差异。我正在使用虚幻编辑器 4.16.0!

我注意到另一件奇怪的事情:当我从 Unreal Engine 编辑器编译所有内容时,它编译并运行良好。但是当我用 VS 2017 编译它时,我得到了错误,而且我也没有得到自动完成,这真是太糟糕了。我错过了什么?

在 PositionReporter.h 上包含 Engine.h 解决了这个问题。

#pragma once

#include "Engine.h" // <- This
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "PositionReporter.generated.h"

您需要给 Intellisense 一些时间...事实上,我关闭并重新打开解决方案以停止显示不存在的错误并提供自动完成功能。

注意: 正如其他帖子中提到的,此解决方案很适合智能感知自动完成,但不是最好的,因为它将包含大量内容并大大增加编译次。 包括特定的 .h 文件会更好,但您需要知道要包括什么 .h,而您可能不知道。

我发现的最佳解决方案是放弃 Intellisense 并使用 Resharper 进行代码自动完成,它运行速度快,自动完成正确,并且您不需要包含任何额外的文件。

我想指出,从 Unreal 4.15 开始,包含 "Engine.h" 与 IWYU 的基本原理背道而驰,因为 Engine.h 很大并且会减慢编译时间。有关此事的更多信息,请参阅 Unreal Documentation。因此,尽管它解决了问题,而且没有什么特别的 'wrong' 这样做 - 它可能不是最好的主意。

另一个更符合 IWYU 的选项是将 Actor.h 包含在 PositionReport.cpp 中,因为 GetOwner 在 AActor class.

#include "PositionReport.h"
#include "GameFramework/Actor.h" //This is the change in PositionReport.cpp