C++ 具有指向C+中成员的指针的结构+;,如何访问它
好的,这是我的代码。我有一个名为employee的结构,它有一个成员char*名称。如何更改name的值C++ 具有指向C+中成员的指针的结构+;,如何访问它,c++,struct,C++,Struct,好的,这是我的代码。我有一个名为employee的结构,它有一个成员char*名称。如何更改name的值 struct employee { char* name; int age; }; int main() { struct employee james; james.age=12; // this line is fine james.name = "james"; // this line is not working cout <
struct employee {
char* name;
int age;
};
int main()
{
struct employee james;
james.age=12; // this line is fine
james.name = "james"; // this line is not working
cout << james.name;
return 0;
}
struct employee{
字符*名称;
智力年龄;
};
int main()
{
struct雇员james;
james.age=12;//这行很好
james.name=“james”//此行不起作用
cout您可以尝试使用strcpy
strcpy(james.name, "james");
使用std::string而不是char*指针,它可以正常工作
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
在源代码中输入的任何文字字符串值(例如“james”
)根据定义是一个const char*
值,const
意味着它在程序运行时不能被更改。在您的类中,name
成员被声明为char*
类型,它不是const
,因此可以在运行时被更改。编译器不允许您分配const char*
>将值指定给类型为char*
的变量,以保持类型为const char*
的值不能修改的不变量。(当然,另一种方法也可以;您可以将char*
值指定给类型为const char*
的变量。)
为了用最少的字符来解决这个问题,您必须在employee
struct定义中将char*name
更改为const char*name
。但是,我同意最好的做法是将其更改为std::string
成员,如@Hamza.S在其答案中所示。std::string
类有一个赋值项由const char*
值构建它的t运算符,因此答案中的行james.name=“james”
实际上将std::string
设置为等于const char*
值“james”
如果您喜欢使用char*,您可以这样做:
#include <iostream>
#include <string.h>
#include <stdlib.h>
struct employee {
char *name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = (char *)malloc(sizeof(char) * 10);
strcpy(james.name, "James");
std::cout << james.name << std::endl;
return 0;
}
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
#包括
#包括
#包括
结构雇员{
字符*名称;
智力年龄;
};
int main(){
雇员詹姆斯;
詹姆斯:年龄=12岁;
james.name=(char*)malloc(sizeof(char)*10);
strcpy(james.name,“james”);
Std::CUT它工作得很好(使用)<代码> STD::String ,并从<代码>结构Suffer-Engor杰姆斯中删除<代码> Stutt<代码>,< /C> >,它不需要在C++中使用。我必须使用CARIF,将指针名称分配给一个文字,尝试将文字字符串声明为静态char *sJAM=“杰姆斯”;然后以与您相同的方式将.name指向sJames。@Euler向您的教授展示:james.name
必须先指向已分配的存储,否则您将写入一个不确定的内存位置您必须在文件顶部包含,这样才能工作。您的char*
示例泄漏记忆
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}