代码

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //string的构造函数
  5. /*
  6. ① string(); //创建一个空字符串 例如:string str;
  7. ② string(const char*s); //使用字符串s初始化
  8. ③ string(const string& str); //使用一个string对象初始化另一个string对象
  9. ④ string(int n,char c); //使用n个字符c初始化
  10. */
  11. void test01(){
  12. string s1;//默认构造//①
  13. const char* str = "hello world";//②
  14. string s2(str);
  15. cout << "s2 = " << s2 << endl;
  16. string s3(s2);//③
  17. cout << "s3 = " << s3 << endl;
  18. string s4(10, 'a');//④
  19. cout << "s4 = " << s4 << endl;
  20. }
  21. int main() {
  22. test01();
  23. return 0;
  24. }

运行结果

image.png