[英]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
。
您可能想要使用前向聲明的主要原因有兩個:
#include
相應頭文件的類的指針。 在我們的特定示例中,這意味着前向聲明 USphereComponent 意味着我們不需要#include "SphereComponent.h"
語句(如果我們只是試圖傳遞一個 USphereComponent 的話)。 通常,當發生這種情況時,#include 語句只是在 .cpp 文件中完成。 減少頭文件中包含的數量有兩個主要優點:
class B;
class A
{
B* foo;
};
class B
{
A* bar;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.