因此,我正在学习 C++ 并学习在我的跨应用程序运行的数据持久性实践中使用 SQLite,这很有趣。
但是我遇到了这个问题:
该程序是一个 Grade Book,经典的 Ditel C++ 书籍练习。我的类(class)结构如下:
~/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 文件,这似乎完全违反直觉,换句话说,我这样做是对的,还是我遗漏了什么?
如果是这样,关于这种“级联”如何工作的一些解释或指示将非常棒。
谢谢!
最佳答案
首先,你的头文件应该使用 include guards 来防止多重包含:
#ifndef MY_HEADER_H
#define MY_HDEADER_H
// code...
#endif // this file will only ever be copied in once to another file
其次,您应该显式地包含所有您需要做的头文件。依靠 header A 为您包含 header B 很笨拙,而且由于您使用的是包含保护,因此您永远不必担心包含同一个文件两次。
因此,要回答您的问题,不,从它可以“更好”的意义上说,它并不“正确”。 main.cpp
应该包含它需要的所有头文件。他们全部。 #include
是一种简单的文本替换机制。当您#include
一个文件时,它会被直接粘贴进去。就是这样。
关于C++ #include,嵌套包含如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15630111/