包含在c ++中的头文件如何工作?我已经在.h文件中实现了类,当有#include两个文件时,出现此错误:
files.h:14:7: error: redefinition of ‘class abstract_file’
files.h:14:20: error: previous definition of ‘class abstract_file’`
Run Code Online (Sandbox Code Playgroud)
每个类和枚举多次.有谁能解释一下?
include在C++中使用只需要包含文件并将内容splats到包含它的位置.要执行此操作而不必担心同一文件的多个包含,您需要使用标头保护.对所有头文件使用此基本格式:
#ifndef FILENAME_H
#define FILENAME_H
class foo (or whatever else is in the file!) {
...
};
#endif
Run Code Online (Sandbox Code Playgroud)
您只能包含一次定义,但可以多次包含标题.要解决此问题,请添加:
#pragma once
Run Code Online (Sandbox Code Playgroud)
到每个头文件的顶部.
虽然#pragma once相对常见,但如果您使用较旧的编译器,则可能不受支持.在这种情况下,您需要依靠手动包括警卫:
#ifndef MY_HEADER_H
#define MY_HEADER_H
...
#endif
Run Code Online (Sandbox Code Playgroud)
(请注意,您需要MY_HEADER_H为每个头文件替换唯一的字符串)