类指针*是什么意思

What does class pointer* mean?

本文关键字:意思 是什么 指针      更新时间:2023-10-16

我得到了这个我不太明白的语法:

class USphereComponent* ProxSphere;

我认为这意味着创建一个类,但这个类是一个指针吗?

但结果只是从现有的类USphereComponent创建一个名为ProxSphere的对象。

此语法实际上是什么意思,它的用法是什么?

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

或者替代方案:

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;做的时候只需要前向声明一次类型,否则就需要使用第一种语法,并在每次使用USphereComponent之前添加class关键字。

您可能想要使用前向声明有两个主要原因:

  1. 这可能是虚幻引擎中前向声明最常见的用法。在头 (.h( 文件中,前向声明允许您使用未为其#include相应头文件的类的指针。在我们的特定示例中,这意味着向前声明 USphereComponent 意味着我们不需要 #include "SphereComponent.h" 语句(如果我们只是试图传递一个 USphereComponent(。

    通常,发生这种情况时,#include 语句只是在.cpp文件中完成的。减少头文件中的包含数量主要有两个优点:

    • 编译时间更快。请注意,这主要对像虚幻引擎这样大的代码库有重大影响。
    • 这减少了模块的公共依赖项的数量(通过使它们"私有",因为您的包含现在在您的.cpp中(。这使您的模块更容易被依赖,也使其界面更简洁。
  2. 就像其他答案所说,当您在同一文件中有两种相互依赖的类型时,前向声明可用于打破循环依赖关系:

    class B;
    class A
    {
        B* foo;
    };
    class B
    {
        A* bar;
    };