我什么时候在C++程序的开头使用'#include <string>'?

xai*_*xai 4 c++ string

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

#include <iostream>
using namespace std;

void printVariable(int number){
    cout << "Johnny's favorite number is" << number << endl
}
Run Code Online (Sandbox Code Playgroud)

但是,在下面的代码中,它确实包含#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;
}
Run Code Online (Sandbox Code Playgroud)

我只#include <string>在变量表示字符串时使用吗?

Lig*_*ica 6

我只#include <string>在变量表示字符串时使用吗?

是.

使用#include <string>具有类型的变量时使用std::string.

"text here"与直觉相反,代码不是std::string; 它是一个字符串文字,一个C风格的字符串,一个const char[10]可转换为const char*.欢迎使用C++及其遗留的奇怪之处.