gpt4 book ai didi

c++ - 头文件使用其他头文件函数

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

头文件是否能够调用其他头文件中的函数。如果是这样,你该怎么做。例如:

void IntStack::push(int n)
{
IntNode *newNode = new IntNode(n);
newNode->next = top;
top = newNode;
return;
}

我能否创建另一个头文件并能够使用此推送功能?

最佳答案

您可以这样做(但是您可能不想这样做,至少对于您链接的示例而言不是这样 - 见下文)。

首先,您可以按照要求执行以下操作:

// a.hpp
#pragma once // or include guards if you can't use pragma once
class IntStack {
...
void push(int n);
...

// b.hpp
#pragma once // or include guards if you can't use pragma once
#include "a.hpp"
void foo() { IntStack i; i.push(0); }

但是,您可能不想这样做。在其他 header 中包含 header 会增加编译时间,通常没有必要。您要做的是在头文件中声明您的类、类型和函数,然后在 cpp 文件中包含各种定义。

以你的例子为例:

// a.hpp
#pragma once // or include guards if you can't use pragma once
class IntStack {
...
void push(int n);
...

// a.cpp
#include "a.hpp"

void IntStack::push(int n) {
IntNode *newNode = new IntNode(n);
newNode->next = top;
top = newNode;
return;
}

// b.hpp
#pragma once // or include guards if you can't use pragma once
void foo();

// b.cpp
void foo() {
IntStack i;
i.push(0);
}

关于c++ - 头文件使用其他头文件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58350856/

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