首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >推荐的C++包括实践

推荐的C++包括实践
EN

Stack Overflow用户
提问于 2021-09-18 04:52:26
回答 2查看 64关注 0票数 0

在下面的场景中,包含<string>头的最佳方法是什么?

main.cpp

代码语言:javascript
复制
#include "extra.h"

int main() {
    func("A string");
    return 0;
}

extra.h

代码语言:javascript
复制
#ifndef EXTRA_H
#define EXTRA_H

    #include <string>

    void func(std::string);

#endif

extra.cpp

代码语言:javascript
复制
#include <iostream>
#include "extra.h"

void func(std::string str) {
    std::cout << str << '\n';
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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,因为它们将一起维护。

票数 3
EN

Stack Overflow用户

发布于 2021-09-18 05:54:31

头文件应该包含尽可能少的内容。这使它保持干净,并且允许更快的编译。如果头文件需要完整的类型,则必须在头文件中包含该类型的包含文件,否则使用前向声明。

例如,main.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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!");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69231700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档