class Student {
public:
string name;
};
对比
class Student {
public:
char* name;
};
如有错误请指正。如果我们要使用 char* 而不是 string,我们将不得不编写自己的复制构造函数,因为每次我们将指针变量作为数据成员时都需要这样做。正确的?
所以,我的问题是:为什么要使用 char*?
使用字符串,在构造函数中,我们可以直接做:
Student(string s) {
name = s;
}
与 char* 相比更简单,需要:
Student(string s) {
name = new char[strlen(s)+1]; // extra 1 to store the '\n'
strcpy(name,s);
}
为什么在用作类的数据成员时不始终使用字符串而不是 char*?
最佳答案
我认为 char*
在 C++ 中用作字符串的唯一原因是因为 C。我确定它是否是一种新语言,一种不努力与C,char*
不会那样使用。您会注意到,将 char*
当作字符串处理的函数都来自 C。
注意在C中,没有字符串,所以
struct Student { char* name; };
是完全有效的 C 代码,而
struct Student { string name; };
不是。因此,在处理以前以 C 为目标的代码时,看到那些 char*
类型并不罕见。
通常没有理由将 char*
用作字符串,除非您要编写新的字符串类、连接 C 函数或处理遗留代码。
关于c++ - string 与 char* 作为类成员变量。为什么要使用 char* 呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399389/