2012-03-26 246 views
1

我有一个C++项目,我正在研究。我现在有点难过。我需要一点帮助。我需要将.h文件中的代码实现到main.cpp文件中,我不知道该怎么做。如何将.h文件中的代码实现到main.cpp文件中?

对于来自main.cpp中的代码示例代码:从.h文件

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

和代码:

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中。你会怎么做?任何帮助apprecaited。我希望我不会把任何人都弄糊涂,因为我需要知道如何去做。由于

+0

包括在您的main.cpp文件.h文件并执行实施。如果您的.cpp文件不是启动文件(不是主文件),那么您必须编写另一个.cpp文件,然后链接到主程序。 – Jagannath 2012-03-26 23:28:20

+0

我的.h文件包含在main.cpp文件的顶部 – Lea 2012-03-26 23:32:25

回答

1

在你需要包含头文件的顶部,这样main.cpp

#include "header_file.h" 

现在,你应该能够自由地调用insert()case 1:下像你想要的。

但是,如果没有实现,这些函数声明实际上不会做太多。所以,你有几个选择。您可以将这些实现放在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 
} 
+0

我有另一个.cpp文件,其中包含.h文件中所有函数的实现。所以我不确定是否需要在main函数中包含其他.cpp文件中的任何内容。 – Lea 2012-03-26 23:55:10

+0

您是否收到任何错误?所发生的是,在源文件全部编译之后,链接器(如其名称所暗示的那样)将它们链接在一起,就好像它们是一个大的编译源文件一样。如果这些实现位于不同的源文件中,则不必担心,链接器应该处理这个问题。 – 2012-03-27 00:03:16

+0

好的。但我仍然不知道如何使用插入在main.cpp中的情况下,当实施是在另一个.cpp文件 – Lea 2012-03-27 00:22:45

0

那么,你是否已经包含了头文件,你应该能够实现任何FUNC您在该标题中声明的内容。例如,你想实现insert功能,您的main.cpp应该是这样的:

#include "myhfile.h" 

void insert(const elemType& item) 
{ 
    // implement here 
} 

int main() 
{ 
    // your switch here 
    // you can now use insert(item) because it is implemented above 
} 
相关问题