c++ - C++ 中具有指向成员的指针的结构,如何访问它

标签 c++ struct

好的,这是我的代码。我有一个名为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/

相关文章:

ios - 尝试在indexpath.row处执行 "swipe left to delete "时出现UITableView SIGBRT错误

c - 如何在 C 中的多个函数中使用结构体?

c++ - Win32 文件 IO 工作但 fopen 等。阿尔。失败。这里发生了什么?

c++ - 将类模板推迟到其构造函数

c++ - 如何将操纵器匹配为模板参数并为特定的操纵器启用函数调用

c++ - 从 C++ 中的函数返回数组

c - 指针未设置为结构数组的元素

c++ - 如何将包含逗号的字符串字符串化?

c - c中带有数组的结构的结果不一致

mongodb - 需要帮助使用 golang 在我的 mongodb 数据库中存储类型接口(interface)的映射