簡體   English   中英

類指針*是什么意思?

[英]What does class pointer* means?

我得到了這個我不太明白的語法:

class USphereComponent* ProxSphere;

我認為這意味着創建一個類,但這個類是一個指針?

但結果只是從現有的類 USphereComponent 創建一個名為 ProxSphere 的對象。

這個語法實際上意味着什么及其用法?

class Someotherclass; that has not been defined yet
class HelloWorld
{
    Someotherclass* my_pointer;
};

or alternative:

class HelloWorld
{
    class Someotherclass* my_pointer;
};

如果您有多個指向尚未定義的類的指針(或引用),則第一個顯然是正確的。

第二個更好? (我不知道)如果你只需要做一次,否則做

class HelloWorld
{
    class Someotherclass* my_pointer;
    class Someotherclass* my_pointer2;
    class Someotherclass* my_pointer3;

    void func(class Someotherclass* my_pointer, class Someotherclass& my_ref);
};

可能不是最好的。

Jts的回答是正確的。 我想為它添加一個用例:

這主要用於當您有圓類依賴項時。

喜歡:

class A { B* binst; };
class B { A* ainst; };

這不會編譯,因為 B 以前不知道。 因此,您將首先聲明 B 類。

class B;
class A { B* binst; };
class B { A* ainst; };

或者如前所述,您可以使用語法糖:

class A { class B* binst; };
class B { A* ainst; };

這種依賴可能是一種代碼異味。 它也可能沒問題,甚至是必要的。 如果你有它,你應該仔細考慮你是否不能用其他一些但方便的方式來做。

該特定語法稱為“前向聲明”。 它用於聲明尚未定義的類型。 這基本上是在告訴編譯器“存在一個名為USphereComponent的類類型,您還沒有看到它會出現在代碼后面的代碼中,如果您看到該類型的指針,請不要對我大喊大叫”。 這允許您為該前向聲明的類型聲明指針和引用

寫作:

class USphereComponent* ProxSphere;

真的就相當於寫這個:

class USphereComponent;
USphereComponent* ProxSphere;

class USphereComponent;語法的唯一區別是,當你像class USphereComponent;這樣的class USphereComponent;做時,你只需要向前聲明一次類型class USphereComponent; ,否則您需要使用第一種語法並在每次使用 USphereComponent 之前添加class USphereComponent

您可能想要使用前向聲明的主要原因有兩個:

  1. 這可能是 Unreal 中最常見的前向聲明用法。 在頭 (.h) 文件中,前向聲明允許您使用沒有#include相應頭文件的類的指針。 在我們的特定示例中,這意味着前向聲明 USphereComponent 意味着我們不需要#include "SphereComponent.h"語句(如果我們只是試圖傳遞一個 USphereComponent 的話)。 通常,當發生這種情況時,#include 語句只是在 .cpp 文件中完成。 減少頭文件中包含的數量有兩個主要優點:
    • 編譯時間更快。 請注意,這主要對像 Unreal 一樣大的代碼庫產生重大影響。
    • 這減少了模塊的公共依賴項的數量(通過使它們“私有”,因為您的包含現在在您的 .cpp 中)。 這使得你的模塊更容易被依賴,也使得它的界面更干凈。
  2. 就像其他答案所說的那樣,當您在同一文件中有 2 種相互依賴的類型時,可以使用前向聲明來打破依賴循環:
class B;
class A 
{
    B* foo;
};
class B
{
    A* bar;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM