gpt4 book ai didi

c++ - class foo; 语句是什么意思?意思是

转载 作者:太空宇宙 更新时间:2023-11-04 15:44:00 25 4
gpt4 key购买 nike

我一直在翻一个项目的代码,遇到了语句

 class foo;
.
.
.
.
foo* f1;

在不同的地方。该类也未在包含的任何 header 中声明。谁能告诉我这是什么意思。

最佳答案

这是一个前向声明。它可用于类、结构和函数,并告诉编译器这是在别处或以后定义的。

对于类,有(至少)两个用例。

1。不需要完整定义

前向声明后,编译器不知道类的大小或成员,只知道名称。这对于指向类的指针(以及基本上是围绕指针的语法糖的引用)来说已经足够了。但通常指针就足够了,这样你就可以避免将整个头文件包含在另一个头文件中。这有助于提高编译速度,避免在一个 header 更改时需要重新编译所有内容。

myfuncs.h

class MyClass; // forward declaration
void helpMyClass(MyClass &needy);

// here this would give compiler error about incomplete type:
//void badHelp(MyClass needy); // value needs definition

我的函数.cpp:

#include "myclass.h" // entire MyClass definition
void helpMyClass(MyClass &needy) {
needy.helpMe(false); // needs full definition
}

这方面的重要用例是所谓的 PIMPL idiom ,在 SO 下也有很好的介绍 标签。

2。两个类需要相互引用

class node; // forward declarion

class collection {
node *frist; // pointer enabled by forward declaration
}

class node {
collection *owner; // already defined above so works too
}

在这种情况下,需要前向声明才能很好地完成这项工作。只是说以防万一你在野外看到它,有一种使用 void 指针和强制转换的丑陋方式,有时在新手程序员不知道应该如何完成时使用。

关于c++ - class foo; 语句是什么意思?意思是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19581406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com