#include <iostream>
using namespace std;
#include <string>
void main1()//string的构造函数
{
string s1 = "aaaaa";
string s2 = s1;//通过拷贝构造函数来初始化s2
string s3("bbbbb");
string s4(10,'a');//带参数的构造函数
string s5;//默认构造函数
cout << s1 << endl;
cout << s2 << endl;
cout << s3<< endl;
cout << s4 << endl;
}
void main2()//数组方式遍历
{
string s1 = "abcdef";
for (int i = 0; i < s1.length(); i++)
{
cout<< s1[i] <<" ";
}
cout << endl;
}
void main3()//迭代器方式遍历
{
string s1 = "abcdef";
for (string::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void main4()//at()方式抛异常
{
string s1 = "abcdef";
try
{
for (int i = 0; i < s1.length() + 3; i++)
{
cout << s1.at(i) << " ";
}
}
catch (...)
{
cout << "发生了异常" << endl;
}
}
void main5()//数组方式方式抛异常
{
string s1 = "abcdef";
try
{
for (int i = 0; i < s1.length() + 3; i++)
{
cout << s1[i] << " ";
}
}
catch (...)
{
cout << "发生了异常" << endl;
}
}
int main()
{
main1();
main2();
main3();
main4();
//main5();
return 0;
}
上面代码执行结果如下图:
构造方法有几种:(1)默认构造函数 (2)拷贝构造函数 (4)带参数的构造函数
抛异常的时候,用at()方法,用数组方式抛异常的话会发生中断,数组越界,发生错误。