gpt4 book ai didi

c++ - 对在头文件中实例化指针感到困惑

转载 作者:行者123 更新时间:2023-11-30 04:11:42 24 4
gpt4 key购买 nike

我正在看一本书,它规定了将什么放入头文件的以下原则:

"What you can put into header files? The basic rule is “only declarations,” that is, only information to the compiler but nothing that allocates storage by generating code or creating variables. This is because the header file will typically be included in several translation units in a project, and if storage for one identifier is allocated in more than one place, the linker will come up with a multiple definition error ..."

但是,它随后给出了此类头文件的示例:

#ifndef STACK_H
#define STACK_H

struct Stack
{
struct Link
{
void* data;
Link* next;
void initialize(void* dat, Link* nxt);
} *head;
...
};

#endif

变量“head”不是一个对象违反了这个规则吗?即使是一个指针,如果多个编译单元包含这个头文件,也会占用存储并导致“多重定义”?

最佳答案

您正在声明一个成员变量。即使它不是指针,也不是问题。它是类(结构)声明的一部分。

只有当你实例化一个Stack类型的对象时,存储分配才会真正发生。

关于c++ - 对在头文件中实例化指针感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20136108/

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