可以使用C风格字符串对string对象进行初始化或赋值
string类型的加法操作需要两个操作数,可以使用C风格字符串作为其中一个操作数,也允许将C风格字符串用作复合赋值操作的右操作数。
在要求使用C风格字符串的地方不可以直接使用标准库string类型对象
无法使用string对象初始化字符串指针:
string st2("hello world");
char *str = st2; //complie-time type error
但是string类提供了一个名为c_str的成员函数,以实现我们的要求
char *str = str2.c_str(); //almost ok,but not quite
c_str函数返回C风格字符串,返回指向字符数组首地址的指针,该数组存放了与string对象相同的内容,并且以结束符null结束。
因为c_str返回的指针指向const char类型的数组,所以上述初始化失败了,这样做是为了避免修改该数组,正确的初始化为:
const char *str = st2.c_str(); //ok
c_str返回的数组并不保证一定是有效的,接下来对st2的操作有可能会改变st2的值,是刚才返回的数组失效。如果程序需要持续访问该数据,则应该复制c_str函数返回的数组。