好的,这是我的代码。我有一个名为employee 的结构,它有一个成员char* 名称。如何更改名称的值?
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;
}
最佳答案
使用 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;
}
或者
如果你想使用 char* 指针,那么使用 const char* name
就可以了。
#include <iostream>
struct employee {
const char* name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
关于c++ - C++ 中具有指向成员的指针的结构,如何访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54359166/