将 header 文件包含到多个继承 类 的最佳实践
The best practice for including header files to multiple inherited classes
假设我们有一个 parent class 和 header parent.h
和 2 child classes child1.h
和child2.h
,因为它们都继承自 parent,所以两个 header 文件都应该包含 parent.h
。在另一个文件中包含 child1.h
和 child2.h
将导致 parent class 的重复定义。避免这种情况的最佳方法是什么?使用 #pragma once
是一种好的做法,还是有其他方法可以解决这个问题?
这就是为什么 #ifndef
被用作检查头文件的确切原因。
例如,您的“parent.h”可能有:
#ifndef PARENT_H
#define PARENT_H
.... //Your header definition
#endif
然后,在child1.h
和child2.h
#ifndef PARENT_H
#include "parent.h"
#endif
....//Your source code
是的,您可以使用 pragma 或 #ifndef
#ifndef _AUTOMOBILE_H
#define _AUTOMOBILE_H
//...
#endif
假设我们有一个 parent class 和 header parent.h
和 2 child classes child1.h
和child2.h
,因为它们都继承自 parent,所以两个 header 文件都应该包含 parent.h
。在另一个文件中包含 child1.h
和 child2.h
将导致 parent class 的重复定义。避免这种情况的最佳方法是什么?使用 #pragma once
是一种好的做法,还是有其他方法可以解决这个问题?
这就是为什么 #ifndef
被用作检查头文件的确切原因。
例如,您的“parent.h”可能有:
#ifndef PARENT_H
#define PARENT_H
.... //Your header definition
#endif
然后,在child1.h
和child2.h
#ifndef PARENT_H
#include "parent.h"
#endif
....//Your source code
是的,您可以使用 pragma 或 #ifndef
#ifndef _AUTOMOBILE_H
#define _AUTOMOBILE_H
//...
#endif