在下面的场景中,包含<string>头的最佳方法是什么?
main.cpp
#include "extra.h"
int main() {
func("A string");
return 0;
}extra.h
#ifndef EXTRA_H
#define EXTRA_H
#include <string>
void func(std::string);
#endifextra.cpp
#include <iostream>
#include "extra.h"
void func(std::string str) {
std::cout << str << '\n';
}发布于 2021-09-18 05:58:13
您的extra.h包括<string>,因为它直接使用它。在您的std::string中没有直接使用main.cpp,所以在其中包含<string>是很奇怪的。
此外,在extra.cpp中包括extra.cpp是完全不必要的,因为std::string的使用是在函数签名中使用的,您知道这是在extra.h中声明的,另外,可以合理地期望两个extra文件的维护可以作为一个操作来完成,所以不必担心extra.h突然不包括<string>,然后破坏extra.cpp,因为它们将一起维护。
发布于 2021-09-18 05:54:31
头文件应该包含尽可能少的内容。这使它保持干净,并且允许更快的编译。如果头文件需要完整的类型,则必须在头文件中包含该类型的包含文件,否则使用前向声明。
例如,main.h
#pragma once
// if your header uses a full type (see function h)
// it needs to know the size of the type
// then include header file for that type in your header
#include <string>
void h(std::string str);
// if your header only has references or pointers to a type
// then add a forward declaration of that type.
// The compiler only has to know the size for the reference/pointer
struct struct_t;
void f(const struct_t& s);
void g(const struct_t* s);然后是main.cpp
#include "main.h"
#include <iostream>
// #include <string> not really needed already done in "main.h"
// full declaration of struct_t in the place where it is needed.
// note this could also be in done in its own header file.
struct struct_t
{
int value1;
int value2;
};
void f(const struct_t& s)
{
std::cout << s.value1 << std::endl;
std::cout << s.value2 << std::endl;
}
void g(const struct_t* s)
{
std::cout << s->value1 << std::endl;
std::cout << s->value2 << std::endl;
}
void h(std::string s)
{
std::cout << s << std::endl;
}
int main()
{
struct_t values{ 0, 42 };
f(values);
g(&values);
h("Hello World!");
}https://stackoverflow.com/questions/69231700
复制相似问题