c++ - (c++) 我需要在新类的头文件中包含什么

标签 c++ string header

在用 C++ 创建新类时,我对某些事情感到好奇。

在我的 main.cpp 中我有这两个:

#include <iostream> 
#incude <string>

但是,在我的另一个类 FeedInfo.h 的头文件中,我需要包含什么才能在那里使用字符串?

例如,如果我想在我的 .h 中创建一个字符串:

std::string feed;

当我只使用 #include <iostream> 时,这段代码将成功编译或者当我只使用 #include <string> -- 或者当我同时使用两者时,当然。

这让我感到困惑,因为在 main.cpp 中我必须同时使用两者 - 但在 .h 文件中我只需要其中之一 - 那么我应该包括哪一个?

谢谢。

最佳答案

在某些实现中 <iostream> header 包括 <string> header 所以你依赖于搭便车。应该避免这种情况,您应该明确包含 <string>使用 std::string 时的标题类型。例如这个:

#include <iostream>

int main() {
   std::string s = "Hello World!";
   std::cout << s;
}

编译when using g++ , 它在使用 Visual C++ 时不编译。所以你应该使用:

#include <iostream>
#include <string>

int main() {
   std::string s = "Hello World!";
   std::cout << s;
}

简而言之,如果你需要一个 std::string - 包括 <string>标题在适当的地方,如果你想将数据发送到标准输出使用 <iostream> .以下是使用头文件和源文件时的 segmentation :

myclass.h:

#ifndef MY_CLASS_H
#define MY_CLASS_H

#include <string>
 // your code

#endif 

我的类.cpp:

#include "myclass.h"
// include other headers as needed

ma​​in.cpp:

#include <iostream>
#include <string>
#include "myclass.h"
//your code

另请查看标题为: How do I include the string header?

关于c++ - (c++) 我需要在新类的头文件中包含什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48131080/

相关文章:

c++ - 带有单个发送消息的 ComboBox 项目选择

C++ AVX2 内在函数非标准大小

c - 向链表中插入一个字符串

javascript - 如何动态检查一个字符串是否包含多个子字符串匹配?

pdf - WkHtmlToX Sharp 如何添加页眉和页脚?

c++ - constexpr 和 RTTI

c++ - 结构体和类的区别

string - 当字符串没有自动触发时如何触发 COW

css - 如何使粘性标题中的文本和图标变黑?

php - 使用 fgetcsv 在浏览器中启用提取和显示外语内容