使用其他头文件功能的头文件

时间:2019-10-12 04:27:44

标签: c++ function header

是能够从其他头文件调用功能的头文件。如果是这样,您该怎么做。 例如:

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

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

1 个答案:

答案 0 :(得分:1)

您可以执行此操作(但是,您可能不希望这样做,至少对于所链接的示例来说不希望-参见下文)。

首先,这是您可以按照要求执行的操作:

// 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); }

但是,您可能不想这样做。在其他标头中包含标头可能会浪费编译时间,通常只是不必要。您要做的是在头文件中包含类,类型和函数的声明,然后在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);
}
相关问题