在C++计划开始时何时使用 '#include <string>'?
When do I use '#include <string>' at the start of a C++ program?
我对在程序开始时使用#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*
) 的指针,而不是一个string
(string
类的实例)。您可以从char*
(包括字符串文本)创建 string
类的实例,方法是将其作为参数传递给 string
的构造函数。但它不是一个字符串,它只是一些误导性的术语。
类似的情况是在数组时调用事物向量。
如果在代码中使用类型std::string
,则应包含<string>
标头。该标头中还有一些其他类型和函数,但std::string
是最常用的类型和函数。
但是,您不需要仅仅为了使用核心语言中内置的字符串文本而包含此标头。
在第一种情况下,不需要库"字符串"。库 "iostream" 支持对象 "cout",因此您有:
#include <iostream>
对于第二种情况,您确实显式使用"字符串",因此需要库"字符串":
#include <string>
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为std::string的某个索引赋值
- <<操作员在下面的行中工作
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数