C ++ #include,嵌套如何包含工作?

时间:2013-03-26 05:39:29

标签: c++ oop include

所以我学习C ++并学习在我的实践中使用SQLite来实现跨应用程序运行的数据持久性,这很有趣。

但我碰到了这个问题:

该课程是一本成绩册,经典的Ditel C ++书籍练习。我按如下方式构建我的类:

~/classes/Database.h/cpp // A small wrapper for sqlite3
~/classes/Student.h/cpp // The Student object with name and grades (Uses Database)
~/classes/GradeBook.h/cpp // Takes care of most of the application logic and UI (Uses Database and Student)
~/main.cpp // contains just the main function and base Instances of Database and GradeBook

这样我就可以从main()实例化单个数据库对象,并通过引用将它传递给GradeBook和Student,这样他们就可以使用数据库函数了。我尝试了所有可能的包含顺序,因为事实证明只有这个订单对我有用。

Student includes Database.
GradeBook includes Student, gets access to Database.
main.cpp includes GradeBook, gets access to both Database and Student.

问题是,这是对的吗?似乎完全违反直觉,包括似乎"级联"从最深的班级到main.cpp文件,换句话说,我这样做是对,还是我错过了什么?

如果是这样的话,可以稍微解释一下这个"级联"作品非常棒。

谢谢!

1 个答案:

答案 0 :(得分:5)

首先,您的头文件应使用包含防护来防止多次包含:

#ifndef MY_HEADER_H
#define MY_HDEADER_H

// code...

#endif  // this file will only ever be copied in once to another file

其次,您应该明确包含所有头文件,这些文件是您需要执行的操作。依靠标题A为你包含标题B只是笨重,因为你使用包含警卫,你永远不必担心两次包含同一个文件。

所以,回答你的问题,不,它可能是“更好”的意义上的“正确”。 main.cpp应包含所需的所有头文件。他们都是。 #include是一种简单的文本替换机制。当你#include一个文件时,它就是字面上粘贴的。就是这样。