我已获得将程序拆分为不同文件的任务。作业是:每个文件都应包含以下内容: customers.h:应包含客户结构的定义和打印客户的声明。 customers.cpp:应包含打印客户的实现(或定义)。 练习1 5.cpp:应包含customers.h和主程序的包含。
这是我的代码:
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 ++的初学者
答案 0 :(得分:2)
void print_customers(customer &head);
C ++编译器以自上而下的方式工作。因此,必须知道它在该点看到的每种类型的标识符。
问题是编译器在上面的语句中不知道类型customer
。尝试在函数的前向声明之前声明类型。
struct customer;
或者在结构定义之后移动函数转发声明。
答案 1 :(得分:2)
首先,
#include "customers.h" // in the "customers.cpp" file.
其次,print_customers
使用customer
,但此类型尚未声明。您有两种方法可以解决问题。
struct customer;
)答案 2 :(得分: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++?