结构错误的重新定义,我只定义了一次

eve*_*veo 10 c++

我真的不明白如何解决这个重定义错误.

COMPILE +错误

g++ main.cpp list.cpp line.cpp
In file included from list.cpp:5:0:
line.h:2:8: error: redefinition of âstruct Lineâ
line.h:2:8: error: previous definition of âstruct Lineâ
Run Code Online (Sandbox Code Playgroud)

main.cpp中

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

int main() {
    int no;
    // List list;

    cout << "List Processor\n==============" << endl;
    cout << "Enter number of items : ";
    cin  >> no;

    // list.set(no);
    // list.display();
}
Run Code Online (Sandbox Code Playgroud)

list.h

#include "line.h"
#define MAX_LINES 10
using namespace std;

struct List{
    private:
        struct Line line[MAX_LINES];
    public:
        void set(int no);
        void display() const;
};
Run Code Online (Sandbox Code Playgroud)

line.h

#define MAX_CHARS 10
struct Line {
    private:
        int num;
        char numOfItem[MAX_CHARS + 1]; // the one is null byte
    public:
        bool set(int n, const char* str);
        void display() const;
};
Run Code Online (Sandbox Code Playgroud)

list.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "list.h"
#include "line.h"

void List::set(int no) {}

void List::display() const {}
Run Code Online (Sandbox Code Playgroud)

line.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "line.h"

bool Line::set(int n, const char* str) {}

void Line::display() const {}
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 22

你需要在标题中加入包含警戒.

#ifndef LIST_H_
#define LIST_H_

// List.h code

#endif
Run Code Online (Sandbox Code Playgroud)

  • @eveo你真的必须使用包含守卫。否则以后你会遇到同样的问题。但最好像您所做的那样删除不必要的包含依赖项。 (2认同)

Cyr*_* Ka 12

在list.cpp中,您包含"line.h"和"list.h".但是"list.h"已经包含"line.h",因此"list.h"实际上包含在代码中两次.(预处理器不够聪明,不能包含已有的东西).

有两种解决方案:

  • 不要在list.cpp文件中直接包含"list.h",但这是一种无法扩展的做法:您必须记住每个头文件包含的内容,并且速度过快.
  • 使用包括警卫,如@juanchopanza所解释