在C++计划开始时何时使用 '#include <string>'?

When do I use '#include <string>' at the start of a C++ program?

本文关键字:lt string gt #include C++ 何时使 计划 开始时      更新时间:2023-10-16

我对在程序开始时使用#include <string>感到困惑。例如,在下面的代码中,我不使用 #include <string>但该函数在运行时仍会打印出字符串"Johnny 最喜欢的数字是"。

#include <iostream>
using namespace std;
void printVariable(int number){
    cout << "Johnny's favorite number is" << number << endl
}

但是,在下面的代码中,它确实包含#include <string>

#include <iostream>
#include <string>
using namespace std;
class Var{
    public:
        void setName(string x){
            name = x;
        }
        string getName(){
           return name;
        }
   private:
       string name;
};
int main(){
    Var Classy;
    Classy.setName("Johnny Bravo");
    cout << Classy.getName() << endl;
    return 0;
}

我是否仅在变量表示字符串时才使用 #include <string>

如果变量表示字符串,我是否只使用 #include <string>

是的。

使用类型为 std::string 的变量时,请使用 #include <string>

直觉相反,代码"text here"不是std::string;它是一个字符串文字,一个C风格的字符串,一个可转换为const char*const char[10]。欢迎来到C++及其传统奇特之处。

您的问题源于您知道像 "aabcd" 这样的东西是字符串文字。所以,它的类型应该是 string .嗯,这并不完全正确。

C++有很多来自C的功能,包括数据类型。因此,这是一个指向 char ( char* ) 的指针,而不是一个stringstring类的实例)。您可以从char*(包括字符串文本)创建 string 类的实例,方法是将其作为参数传递给 string 的构造函数。但它不是一个字符串,它只是一些误导性的术语。

类似的情况是在数组时调用事物向量。

如果在代码中使用类型std::string,则应包含<string>标头。该标头中还有一些其他类型和函数,但std::string是最常用的类型和函数。

但是,您不需要仅仅为了使用核心语言中内置的字符串文本而包含此标头。

在第一种情况下,不需要库"字符串"。库 "iostream" 支持对象 "cout",因此您有:

#include <iostream>

对于第二种情况,您确实显式使用"字符串",因此需要库"字符串":

#include <string>