2013-10-21 52 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;