【问题标题】:C++ Separate Implementation and header filesC++ 分离实现和头文件
【发布时间】:2013-10-21 20:30:22
【问题描述】:

我被分配了将程序拆分为不同文件的任务。任务是:每个文件都应包含以下内容: 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++的初学者

【问题讨论】:

    标签: c++


    【解决方案1】:
    void print_customers(customer &head);
    

    C++ 编译器以自上而下的方式工作。因此,它在该点看到的每种类型和标识符都必须是已知的。

    问题是编译器不知道上面语句中的类型customer。尝试在函数的前向声明之前前向声明类型。

    struct customer;
    

    或者将函数前向声明移到结构定义之后。

    【讨论】:

      【解决方案2】:

      首先,

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

      其次,print_customers 使用了customer,但是这个类型还没有被声明。您有两种方法可以解决此问题。

      1. 将函数声明放在结构声明之后。
      2. 在函数声明之前放置一个转发声明 (struct customer;),

      【讨论】:

        【解决方案3】:

        您需要在customers.h 中进行一些更改。查看代码中的 cmets。

        #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);
        

        然后您必须在customers.cpp#include "customers.h"

        注意我没有在头文件中写using namespace std。因为这会将std 命名空间导入到包含customer.h 的任何内容中。更多详情见:Why is including "using namespace" into a header file a bad idea in C++?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多