类指针*是什么意思
What does class pointer* mean?
我得到了这个我不太明白的语法:
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
关键字。
您可能想要使用前向声明有两个主要原因:
这可能是虚幻引擎中前向声明最常见的用法。在头 (.h( 文件中,前向声明允许您使用未为其
#include
相应头文件的类的指针。在我们的特定示例中,这意味着向前声明 USphereComponent 意味着我们不需要#include "SphereComponent.h"
语句(如果我们只是试图传递一个 USphereComponent(。通常,发生这种情况时,#include 语句只是在.cpp文件中完成的。减少头文件中的包含数量主要有两个优点:
- 编译时间更快。请注意,这主要对像虚幻引擎这样大的代码库有重大影响。
- 这减少了模块的公共依赖项的数量(通过使它们"私有",因为您的包含现在在您的.cpp中(。这使您的模块更容易被依赖,也使其界面更简洁。
就像其他答案所说,当您在同一文件中有两种相互依赖的类型时,前向声明可用于打破循环依赖关系:
class B; class A { B* foo; }; class B { A* bar; };
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 线应该是什么意思
- "CID"在AT+HTTPPARA= "CID" ,1中是什么意思
- 表达式"b=(b-x)&x"是什么意思?
- 这个表达是什么意思?
- 此代码验证公式是什么意思?
- 跟踪日志中的T.11803()是什么意思?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- * 和 ** 在 C++ 函数声明中是什么意思?
- _T("xyz")是什么意思?
- #define Dbg(fmt,..) (0) 是什么意思? 警告:表达式无效
- 这行代码到底是什么意思?
- 当我们说在执行程序时将操作系统的控制权传递给main()函数时,我们的意思是什么
- 这句话在c++中的意思是什么
- 这个typedef的意思是什么
- 这句话的意思是什么
- 意思是什么
- 这个句法的意思是什么?