c++知识点
string类的构造函数和对象定义
string类的构造函数原型: (记住就好)
1.string(); //默认构造函数,创造空串
2.string(const char *s); //用字符串来构造新字符串
3.string(const char *s,unsigned n); //用字符串前n个字符来构造新串
4.string(const string& str); //用str拷贝构造新串
5.string(const str& str,unsigned p,unsigned n); //str从p位置开始构造n个新字符串
6.string(unsigned n,char c); //将c重复n次构造
7.string(first,last); //用序列(first,last)中的内容构造新字符串
下面用简单易懂的代码来帮助理解
#include<iostream>
#include<vector>
#include<string>
using namespace std;
typedef vector<char> CharVector;
int main()
{
char strArr[] = "ABCDEF";
const int num = sizeof(strArr) / sizeof(char); //计算字符个数
CharVector v(strArr, strArr + num); //向量构造
string s1, s2("123456");
cout << "s2=" << s2 << endl;
string s3(s2); //s3=s2
cout << "s3=" << s3 << endl;
string s4(strArr, 5); //用字符串strArr的前5个字符来构造新串
cout << "s4=" << s4 << endl;
string s5(s2, 2, 3); //从字符数组s2的[2]位置开始构造3个字符
cout << "s5=" << s5 << endl;
string s6(6, 'a');
cout << "s6=" << s6 << endl; //将字符‘a’重复6次来构造新字符串
string s7(v.begin(), v.end()); //从strArr[first,last)构造新字符串
cout << "s7=" << s7 << endl;
return 0;
}
输出为:
s2=123456
s3=123456
s4=ABCDE
s5=345
s6=aaaaaa
s7=ABCDEF