c_str函数的返回值是const char*的,不能直接赋值給char*,所以就需要我们进行相应的操作转化,下面就是这一转化过程。
c++语言提供了两种字符串实现,其中较原始的一种只是字符串的c语言实现。与C语言的其他部分一样,它在c+的所有实现中可用,我们将这种实现提供的字符串对象,归为c-串,每个c-串char*类型的。
标准头文件<cstring>包含操作c-串的函数库。这些库函数表达了我们希望使用的几乎每种字符串操作。
当调用库函数,客户程序提供的是string类型参数,而库函数内部实现用的是c-串,因此需要将string对象,转化为char*对象,而c_str()提供了这样一种方法,它返回一个客户程序可读不可改的指向字符数组的指针。
例:
#include <iostream> #include <string> using std::string;
void main()
{ string add_to="hello!"; const string add_on="baby"; const char*cfirst = add_to.c_str(); const char*csecond = add_on.c_str(); char*copy = new char[strlen(cfirst) + strlen(csecond) + 1]; strcpy( copy, cfirst); strcat( copy, csecond); add_to = copy; delete [] copy; std::cout<<add_to<<std::endl;
}
|
看下面一段程序
#include<string>
#include<iostream>
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
using namespace std;
class Student
{
public:
Student(int n,string nam,char s) //定义构造函数
{
num = n;
13行 name = nam;
sex = s;
cout << "Constructor called." << endl;
}
~Student() //定义析构函数
{
cout << "Destructor called." << endl;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl << endl;
}
private:
int num;
char name[10];
char sex;
};
int main()
{
Student stud1(10010,"Wang_li",'f'); //建立对象stud1
stud1.display(); //输出stud1的数据
Student stud2(10011,"Zhang_fun",'m');
stud2.display();
return 0;
}
在VC++6.0中编译会出下面的错误
(13) : error C2440: '=' : cannot convert from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'char [10]'
如果把第13行用c_str()来处理,程序就可以编译通过。即把Studeng类改写成
class Student
{
public:
Student(int n,string nam,char s) //定义构造函数
{
num = n;
strcpy(name,nam.c_str());
sex = s;
cout << "Constructor called." << endl;
}
~Student() //定义析构函数
{
cout << "Destructor called." << endl;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl << endl;
}
private:
int num;
char name[10];
char sex;
};
另一种修改方法是把Student类改写成如下,因为string已经重载了“=”操作符
class Student
{
public:
Student(int n,string nam,char s) //定义构造函数
{
num = n;
name = nam;
sex = s;
cout << "Constructor called." << endl;
}
~Student() //定义析构函数
{
cout << "Destructor called." << endl;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl << endl;
}
private:
int num;
string name;
char sex;
};
转载于:https://blog.51cto.com/pandahsu/165962