Say we have this header file:
#pragma once
#include <vector>
class MyClass
{
public:
MyClass(double);
/* ... */
private:
std::vector<double> internal_values;
};
Run Code Online (Sandbox Code Playgroud)
Now, whenever we use #include "MyClass.hpp" in some other hpp or cpp file, we effectively also #include <vector>, despite the fact that we do not need it. The reason I am saying it is not needed is that std::vector is only used internally in MyClass, but it is not required at all to actually interact …
我有一个关于头文件,包含语句和良好编码风格的快速问题.假设我有2个类,包含相关的源文件和头文件,然后是main()所在的最终源文件.
在Foo.hpp中,我有以下声明:
#include <string>
#include <iostream>
#include <exception>
Run Code Online (Sandbox Code Playgroud)
现在有了Bar.hpp我有以下声明:
#include "Foo.hpp"
#include <string>
Run Code Online (Sandbox Code Playgroud)
最后使用Myprogram.cpp我有以下声明:
#include "Bar.hpp"
#include <string>
#include <iostream>
#include <exception>
Run Code Online (Sandbox Code Playgroud)
我知道Myprogram.cpp中的<>中的include语句和Bar.hpp对于程序编译和运行不是必需的,但是最好的做法或正确的做法是什么?有没有理由不在每个文件中明确包含必要的头文件?