为什么我不能将某些字符串作为分配为结构一部分的“字符串”对象变量?
struct person
{
string firstname;
string lastname;
int age;
char grade;
};
int main()
{
person * pupil = new person;
char temp[] = "Test";
strcpy(pupil->firstname, temp); // THIS IS INVALID, WHY?
return 0;
}
答案 0 :(得分:4)
std::strings
不是普通字符数组,不能直接用作strncpy
的目标。
对于您的代码,您只需将字符串文字分配给现有的string
对象,例如person
对象的数据成员。该字符串将根据文字创建内部副本。例如,
person pupil;
pupil.firstname = "Test";
std::cout << pupil.firstname << std::endl; // prints "Test"
注意,不需要动态分配person
个对象。也不需要临时char
数组。
请注意,在您的情况下,您还可以使用括号括起初始化列表初始化成员:
person pupil = { "John", "Doe", 42, 'F' };
答案 1 :(得分:1)
因为pupil->firstname
不是字符指针。
为什么不读取std:string并将其与strcpy的手册页进行比较
答案 2 :(得分:0)
因为strcpy
适用于C风格的字符串(char缓冲区),而std::string
不是C风格的字符串。
您可以这样做:
pupil->firstname = temp;
或者,完全避免使用temp
:
pupil->firstname = "Test";
更好的是,让person
的构造函数实际构造一个完全形成的对象:
struct person
{
person ()
:
firstname ("Test")
{
}
string firstname;
string lastname;
int age;
char grade;
};
int main()
{
person * pupil = new person;
}