c++ - 我如何将 .h 文件中的代码实现到 main.cpp 文件中?

标签 c++

我有一个正在处理的 C++ 项目。我现在有点难过。我需要一点帮助。我需要将 .h 文件中的代码实现到 main.cpp 文件中,但我不确定该怎么做。

例如来自 main.cpp 的代码代码:

switch (choice){
case 1: // open an account
    {
    cout << "Please enter the opening balence: $ ";
    cin >> openBal;
    cout << endl;
    cout << "Please enter the account number: ";
    cin >> accountNum;
    cout << endl;

    break;
    }
case 2:// check an account
    {
    cout << "Please enter the account number: ";
    cin >> accountNum;
    cout << endl;
    break;
    }

和 .h 文件中的代码:

void display(ostream& out) const;
// displays every item in this list through out

bool retrieve(elemType& item) const;
// retrieves item from this list
// returns true if item is present in this list and
//              element in this list is copied to item
//         false otherwise

// transformers
void insert(const elemType& item);
// inserts item into this list
// preconditions: list is not full and
//                item not present in this list
// postcondition: item is in this list

在 .h 文件中,您需要在情况 1 下的 main.cpp 中的转换器下使用 void 插入。您会怎么做?任何帮助都表示赞赏。我希望我没有让任何人对我需要知道该怎么做感到困惑。谢谢

最佳答案

main.cpp 中,您需要在顶部包含头文件,如下所示:

#include "header_file.h"

现在您应该可以在 case 1: 下自由调用 insert(),如您所愿。

但是,如果没有实现,这些函数声明实际上不会做太多事情。所以,你有几个选择。您可以将实现放在 main.cpp 中,或者您可以创建一个新的 .cpp 文件来保存这些函数的实现。 (别担心,链接器会处理整个“单独的源文件”业务)

在头文件中声明函数并在 cpp 文件中实现它们的最基本方法如下所示:

foo.h 文件:

void insert(const elemType& item); // This is your declaration

foo.cpp 文件:

#include "foo.h"
void insert(const elemType& item)
{
    // Function should do its job here, this is your implementation
}

关于c++ - 我如何将 .h 文件中的代码实现到 main.cpp 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9881335/

相关文章:

c++ - 使用 Howard Hinnant 的 date.h 计算某个日期今年的天数

c++ - 通过EDSDK并行控制佳能相机

c++ - 在 Boost Spirit Qi 中,我如何将每个字符匹配到下一个空格(带预跳过)

c++ - MPFR:未定义引用|安装不正确?

c++ - 为 DiagonalMatrix 对象重载 operator()

带有宏的 C++ 嵌套命名空间

c++ - DLL 导出 4 个 COM 函数但不导出 COM 对象?!我就是不明白!

c++ - 来自西门子的日期和时间

c++ - VS2010 中的浮点自省(introspection) - 如何在不中断的情况下进行检查?

c++ - 使用python运行C++程序并测试