【问题标题】:Redefinition of struct error, I only defined it oncestruct error的重新定义,我只定义了一次
【发布时间】:2013-02-23 15:57:21
【问题描述】:

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

编译+错误

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â

ma​​in.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();
}

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

【问题讨论】:

标签: c++


【解决方案1】:

您需要在标题中输入include guards

#ifndef LIST_H_
#define LIST_H_

// List.h code

#endif

【讨论】:

  • 这是 CPP 课程的介绍。没有其他人使用这样的代码,我也不能,因为我们没有在课堂上讨论这个。抱歉,重新定义必须有另一个更简单的解决方案。
  • 实际上,我所要做的就是在我的list.cpp 中删除#include line.h。无论如何,谢谢!
  • @eveo 你真的必须使用包含防护。否则你以后会遇到同样的问题。但是最好像您所做的那样删除不必要的包含依赖项。
  • 我以后会记住这一点,但在本入门课程的范围内,这不是必需的/不允许的。
  • @user124384 那有什么相关性?你甚至没有描述一个问题。
【解决方案2】:

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

有两种解决方案:

  • 不要将“list.h”直接包含在您的 list.cpp 文件中,但这是一种无法扩展的做法:您必须记住每个头文件包含的内容,这会很快。
  • 如@juanchopanza 所解释,使用包含警卫

【讨论】:

  • 原来如此!从 list.cpp 中删除了 line.h,因为包括 list.h 已经包含 line.h。谢谢。
【解决方案3】:

您包含“line.h”两次,并且您的头文件中没有包含保护。

如果你添加类似的东西:

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

到你的头文件,一切都会好起来的。

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 2018-01-20
    • 2015-09-22
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多