2012-03-26 18 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 
} 
相關問題