我有一个正在处理的 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/