在C++中并没有所谓JAVA的interface接口。
只是通常使用虚基类,纯虚函数达到类似功能。
UE4中提供了一个接口类来达到该功能。
以下是新建的接口类的头文件代码,源文件代码是空的,并没有什么内容。
1 UINTERFACE(MinimalAPI)
2 class UMyInterface : public UInterface
3 {
4 GENERATED_BODY()
5 };
6
7 /**
8 *
9 */
10 class MYPROJECT7_INTERFACE_API IMyInterface
11 {
12 GENERATED_BODY()
13
14 // Add interface functions to this class. This is the class that will be inherited to implement this interface.
//其他类实现本接口,实际上使用的是这个API接口,是IMyInterface而并非上面的UMyInterface。
15 public:
16
17 virtual void showinfo() = 0;
18
19 };
这里使用了纯虚函数,使得这个接口类是虚基类。
新建一个ACTOR类,让其实现IMyInterface接口。
以下是ACTOR类头文件:
1 // Fill out your copyright notice in the Description page of Project Settings.
2
3 #pragma once
4
5 #include "CoreMinimal.h"
6 #include "GameFramework/Actor.h"
7 #include "MyInterface.h"
8 #include "MyActor.generated.h"
9
10 UCLASS()
11 class MYPROJECT7_INTERFACE_API AMyActor : public AActor,public IMyInterface
12 {
13 GENERATED_BODY()
14
15 public:
16 // Sets default values for this actor's properties
17 AMyActor();
18
19 protected:
20 // Called when the game starts or when spawned
21 virtual void BeginPlay() override;
22
23 public: 24 // Called every frame 25 virtual void Tick(float DeltaTime) override; 26 27 virtual void showinfo() override; 28 };
以下是ACTOR类源文件:
1 // Fill out your copyright notice in the Description page of Project Settings.
2
3
4 #include "MyActor.h"
5 #include "Engine.h"
6
7
8 // Sets default values
9 AMyActor::AMyActor()
10 {
11 // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
12 PrimaryActorTick.bCanEverTick = true;
13
14 }
15
16 // Called when the game starts or when spawned
17 void AMyActor::BeginPlay()
18 {
19 Super::BeginPlay();
20 showinfo();
21
22 }
23
24 // Called every frame
25 void AMyActor::Tick(float DeltaTime)
26 {
27 Super::Tick(DeltaTime);
28
29 }
30
31 void AMyActor::showinfo()
32 {
33 GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, TEXT("Interface"));
34 }
实现接口中的showinfo方法。
效果图如下: