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

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

本文关键字:类型 指针 UactorComponent GetOwner const 不允许 AActor      更新时间:2023-10-16

我是UE4开发的新手,我学习了Udemy的虚幻引擎开发课程。我在Actor上创建了一个新的组件,名为PositionReporter,标题为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;
};

和位置报告器中的代码.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()"时,我收到编译器错误"不允许指向不完整类类型的指针"。

做错了什么?我是否缺少导入?我已经将我的代码与 Ben 的 git 存储库进行了比较,但找不到任何差异。我使用的是虚幻编辑器4.16.0!

我注意到另一件奇怪的事情:当我从虚幻引擎编辑器编译所有内容时,它编译并运行良好。但是当我使用 VS 2017 编译它时,我收到错误,而且我也没有获得自动完成功能,这真是令人沮丧。我错过了什么?

在 PositionReporter.h 上包含 Engine.h 可以解决此问题。

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

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

注意:正如其他帖子中提到的,此解决方案对于获得智能感知自动完成功能很好,但不是最好的,因为它将包含大量内容并大大增加编译时间。 包含特定的 .h 文件会更好,但您需要知道要包含哪些 .h,而且您可能不知道。

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

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

另一个更符合IWYU的选择是将Actor.h包含在PositionReport中.cpp因为GetOwner属于AActor类。

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