c++ string 对象初始化
时间: 2023-09-03 13:07:09 浏览: 114
在 C++ 中,可以使用以下方式初始化字符串对象:
1. 直接赋值:
```
std::string str = "Hello, world!";
```
2. 使用构造函数:
```
std::string str("Hello, world!");
```
3. 使用字符数组初始化:
```
char arr[] = "Hello, world!";
std::string str(arr);
```
4. 使用 std::initializer_list 初始化:
```
std::string str = {"Hello", ", ", "world", "!"};
```
需要注意的是,使用字符数组初始化时,如果字符数组中包含空字符 '\0',则字符串对象只会包含空字符之前的部分。
相关问题
C++ 中string怎么初始化
在C++中,string可以通过多种方式进行初始化:
1. 直接初始化:
```c++
std::string str1("Hello World");
```
2. 拷贝初始化:
```c++
std::string str2 = "Hello World";
```
3. 赋值初始化:
```c++
std::string str3;
str3 = "Hello World";
```
4. 使用默认构造函数初始化:
```c++
std::string str4;
```
5. 使用重载的构造函数初始化:
```c++
std::string str5(10, 'a'); //初始化为 "aaaaaaaaaa"
```
需要注意的是,以上初始化方式都可以用于string对象的初始化,但有些情况下使用某种方式更为合适,例如如果你已经有一个char数组,可以使用拷贝初始化来初始化string对象。
c++ string类型变量初始化
C++中有多种初始化string类型变量的方式,以下是其中的几种:
1. 直接赋值初始化
```c++
std::string str1 = "Hello World";
```
2. 拷贝初始化
```c++
std::string str2("Hello World");
```
3. 使用字符串字面值初始化
```c++
std::string str3 = std::string("Hello World");
```
4. 使用括号初始化
```c++
std::string str4{"Hello World"};
```
5. 使用构造函数初始化
```c++
std::string str5(10, 'a'); // 初始化为"aaaaaaaaaa"
```
6. 使用“+=”运算符连接字符串
```c++
std::string str6 = "Hello";
str6 += " World";
```
注意:以上方式中,第5种方式是使用构造函数初始化,而不是直接初始化。
阅读全文
相关推荐













