在 C++ 中,-> 是成员访问运算符,主要用于通过指针访问对象的成员(包括成员变量和成员函数)。它的作用类似于 . 运算符,但 -> 专门用于指针,而 . 用于直接访问对象

基本用法

假设有一个类 MyClass 和一个指向该类实例的指针 ptr

cpp

运行

class MyClass {
public:
    int Value;
    void Print() { /* 实现 */ }
};

MyClass* ptr = new MyClass(); // 创建对象并获取指针

通过 -> 访问成员:

cpp

运行

ptr->Value = 10; // 访问成员变量
ptr->Print();    // 调用成员函数

等价于先通过解引用指针(*)后用 . 访问:

cpp

运行

(*ptr).Value = 10;
(*ptr).Print();

-> 本质上是 (*ptr).member 的简化写法,使代码更简洁。

在 Unreal Engine 中的常见场景

UE 代码中大量使用指针(如 UObject*AActor* 等),因此 -> 非常常见:

  1. 访问 Actor 组件

    cpp

    运行

    APlayerCharacter* Player = GetPlayerCharacter();
    if (Player) {
        Player->Health = 100; // 访问成员变量
        Player->Jump();       // 调用成员函数
    }
    
  2. 操作 UI 控件

    cpp

    运行

    UButton* LoginButton = GetLoginButton();
    if (LoginButton) {
        LoginButton->SetIsEnabled(true); // 调用按钮的成员函数
    }
    
  3. 调用蓝图函数库

    cpp

    运行

    UGameplayStatics::GetPlayerController(GetWorld(), 0)->SetInputMode(...);
    

注意事项

  • 必须确保指针指向有效的对象(非 nullptr),否则使用 -> 会导致空指针崩溃。因此 UE 代码中通常会先检查指针有效性:

    cpp

    运行

    if (MyPointer) { // 检查指针不为空
        MyPointer->DoSomething();
    }
    
  • -> 只能用于指针类型,直接访问对象时必须用 .

    cpp

    运行

    MyClass obj;
    obj.Value = 5; // 正确:用 . 访问对象
    // obj->Value = 5; // 错误:obj 不是指针
    

    总结:-> 是 C++ 中通过指针访问对象成员的专用运算符,在 UE 开发中频繁用于操作各种指针类型(如 Actor、Widget、Component 等),是连接指针与对象成员的核心语法。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐