2

プログラムを複数のファイルに分割する任務を与えられました。割り当ては次のとおりです。 各ファイルには次のものが含まれている必要があります。 customers.h: 顧客構造の定義と印刷顧客の宣言が含まれている必要があります。customers.cpp: 印刷顧客向けの実装 (または定義) を含める必要があります。演習 1 5.cpp: customers.h とメイン プログラムのインクルードを含める必要があります。

これが私のコードです:

顧客.h

#pragma once;

void print_customers(customer &head);

struct customer
{
string name;
customer *next;

};

顧客.cpp

#include <iostream>

using namespace std;

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

}

}

練習_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 ++の初心者です

4

3 に答える 3

2
void print_customers(customer &head);

C++ コンパイラは上から下へのアプローチで動作します。そのため、その時点で検出されるすべてのタイプ、識別子は認識されている必要があります。

customer問題は、コンパイラが上記のステートメントの型を認識していないことです。関数の前方宣言の前に型を前方宣言してみてください。

struct customer;

または、構造体定義の後に関数前方宣言を移動します。

于 2013-10-21T20:32:13.757 に答える
2

初め、

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

次に、print_customersを使用しますcustomerが、この型はまだ宣言されていません。問題を解決するには 2 つの方法があります。

  1. 構造体の宣言の後に関数の宣言を置きます。
  2. struct customer;関数の宣言の前にforwarded 宣言 ( ) を置き、
于 2013-10-21T20:32:58.973 に答える
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 include "using namespace" into a header file a bad idea in C++?

于 2013-10-21T20:38:20.497 に答える