9.6.1

    技术2025-08-06  19

    int main(){   //string s(1); error string不支持单个容器长度作为参数的构造函数

     string s;                //创建string对象时不提供任何参数得到空string

     string a(3,'a'); cout<<a<<endl;   //aaa

     

     string b(a.begin (),a.end());//将新对象初始化为另一个对象的副本  cout<<b<<endl;                  //aaa

     

     char *p="welcome"; string c(p);         //用p所指向的(以NULL结束)C风格字符串初始化 cout<<c<<endl; //welcome

      char q[]={'a','b','c'};  /* string c2(q);   没有以null结束,无法检测到的严重错误 cout<<c2<<endl; */

     

     string d(q,q+3); //指向数组的指针和一个计数器作为构造函数参数(不必以空字符结束)                           //数组作为参数传递,自动转换为指向数组的第一个元素 cout<<d<<endl;//abc

     

     //用一个string对象初始化另一个string对象 string e="hello"; string f(e,1,2);  //起点和个数 cout<<f<<endl;//el 最多只能复制与e长度相等的字符

     system ("pause");

     }

    最新回复(0)