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

Redefinition of struct error, I only defined it once

本文关键字:定义 一次 新定义 结构 错误      更新时间:2023-10-16

我真的不明白如何修复这个重新定义错误。

编译+错误

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â

main.cpp

#include <iostream>
using namespace std;
#include "list.h"
int main() {
    int no;
    // List list;
    cout << "List Processorn==============" << endl;
    cout << "Enter number of items : ";
    cin  >> no;
    // list.set(no);
    // list.display();
}

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;
};

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;
};

list.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "list.h"
#include "line.h"
void List::set(int no) {}
void List::display() const {}

line.cpp

#include <iostream>
#include <cstring>
using namespace std;
#include "line.h"
bool Line::set(int n, const char* str) {}
void Line::display() const {}

您需要在标头中放置include保护。

#ifndef LIST_H_
#define LIST_H_
// List.h code
#endif

在list.cpp中,您同时包含了"line.h"answers"list.h"。但是"list.h"已经包含了"line.h",所以"list.h"实际上在代码中包含了两次。(预处理器不够聪明,不包括它已经拥有的东西)。

有两种解决方案:

  • 不要直接在list.cpp文件中包含"list.h",但这是一种不可扩展的做法:你必须记住每个头文件都包含了什么,这太快了
  • 使用包括警卫,正如@juancopanza所解释的

您包含了两次"line.h",并且在头文件中没有包含保护。

如果您添加类似以下内容:

 #ifndef LINE_H
 #define LINE_H
 ... rest of header file goes here ... 
 #endif

对于你的头文件,一切都会很好。