2013-10-21 50 views
2

我已經被賦予了將一個程序分成不同文件的任務。分配是:每個文件應包含以下內容: customers.h:應包含客戶結構的定義和打印客戶的聲明。 customers.cpp:應包含打印客戶的實現(或定義)。 練習1 5.cpp:應包含customers.h和主程序。C++單獨實現和頭文件

這裏是我的代碼:

customers.h

#pragma once; 

void print_customers(customer &head); 

struct customer 
{ 
string name; 
customer *next; 

}; 

customers.cpp

#include <iostream> 

using namespace std; 

void print_customers(customer &head) 
{ 
customer *cur = &head; 
while (cur != NULL) 
{ 
    cout << cur->name << endl; 
    cur = cur->next; 

} 

} 

exercise_1_5.cpp

#include <iostream> 
#include <string> 
#include "customers.h" 
using namespace std; 

main() 
{ 
    customer customer1, customer2, customer3; 
    customer1.next = &customer2; 
    customer2.next = &customer3; 

    customer3.next = NULL; 
    customer1.name = "Jack"; 
    customer2.name = "Jane"; 
    customer3.name = "Joe"; 
    print_customers(customer1); 
    return 0; 
} 

它編譯和運行在一個單一的節目很好,但是當我嘗試將它拆分並用g++ -o customers.cpp

我收到此錯誤編譯

customers.cpp:4:22: error: variable or field ‘print_customers’ declared void 
customers.cpp:4:22: error: ‘customer’ was not declared in this scope 
customers.cpp:4:32: error: ‘head’ was not declared in this scope 

誰能幫助,我只是一個初學者使用C++

回答

1

有許多您在customers.h需要改變的。請參閱代碼中的註釋。

#pragma once; 

#include <string>  // including string as it is referenced in the struct 

struct customer 
{ 
    std::string name; // using std qualifer in header 
    customer *next; 
}; 

// moved to below the struct, so that customer is known about 
void print_customers(customer &head); 

之後,您必須在#include "customers.h"customers.cpp

注意我在頭文件中沒有寫using namespace std。因爲這會將std名稱空間導入包含customer.h的任何內容。欲瞭解更多詳情,請參閱:Why is including "using namespace" into a header file a bad idea in C++?

+0

非常有見識和明確的支持。謝謝! – user1816464

+0

@ user1816464謝謝:) – Steve

2
void print_customers(customer &head); 

C++編譯器以上下方式工作。因此,它所看到的每一種類型,標識符都必須知道。

問題是編譯器在上面的語句中不知道類型customer。嘗試在函數的前向聲明前向前聲明該類型。

struct customer; 

或者在struct定義之後移動函數forward聲明。

2

首先,

#include "customers.h" // in the "customers.cpp" file. 

其次,print_customers使用customer,但這種類型尚未宣佈。你有兩種方法來解決這個問題。

  1. 在聲明結構體後放置函數聲明。
  2. 函數的聲明之前放置一個轉發聲明(struct customer;