结构错误的重新定义,我只定义过一次
Redefinition of struct error, I only defined it once
我真的不明白如何修复这个重新定义错误。
编译+错误
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
对于你的头文件,一切都会很好。
相关文章:
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 如何一次删除"cmake -D"定义的所有变量?
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 如何在两个不同的命名空间(但只写一次)中使用相同的标头定义,命名空间有不同的实现?
- 为什么 #pragma 一次不防范多个非 constexpr 定义?
- 组合宏定义以一次获得多个定义 [avr C++]
- CMAKE自定义目标仅运行一次
- 如何一次定义几个功能,仅因名称而差异(不使用宏)
- 为什么一个成员函数只存在一次,甚至在一个包含多个的.h文件中定义?
- 如何在程序中声明/定义一次并在两个类中使用映射列表
- 在继承层次结构中将方法定义为虚拟方法一次,以使多态性发挥作用
- 定义结构并在一次传递中创建相关数据项的列表
- 子访问父变量/定义变量一次,在整个应用程序中使用
- 为什么我不能一次定义两个指针
- 如何在c++中编写一次定义变量的条件
- sort——给定一个自定义排序函数,在一次比较中可以进行多个排序查询
- 结构错误的重新定义,我只定义过一次
- #pragma 一次不会阻止多个变量定义
- 多个符号定义,但我只定义我的符号一次