如何在成员初始化项列表中初始化数组

How to initialize an array in the member initializer list

本文关键字:初始化 列表 数组 成员      更新时间:2023-10-16

完成c++初学。

这是一个成员初始化列表:

Student.cpp

Student::Student(int studentID ,char studentName[40]) : id(studentID), name(studentName){};

Student.h

class Student{
protected:
    char name[40];
    int id;
}

我的问题是namechar[40]类型,因此,name(studentName)显示错误:

a value of type "char *" cannot be used to initialize an entity of type "char [40]"

如何在成员初始化列表中将name数组初始化为studentName数组?我不想使用字符串,我试过strcpy,没有工作

由于不能用其他数组初始化(原始)数组,甚至不能在c++中赋值数组,因此基本上有两种可能性:

  1. 惯用的c++方法是使用std::string,这样任务就变得微不足道了:

    class Student{
    public:
        Student(int studentID, const std::string& studentName)
        : id(studentID), name(studentName) {}
    protected:
        std::string name;
        int id;
    };
    

    然后,当需要时,您可以通过调用c_str成员函数从name获得底层原始char数组:

    const char* CStringName = name.c_str();
    
  2. 如果你想使用char数组,事情会变得更复杂。您可以首先默认初始化数组,然后在构造函数体中填充strcpy:

    class Student{
    public:
        Student(int studentID, const char* studentName)
        : id(studentID) {
            assert(strlen(studentName) < 40); // make sure the given string fits in the array
            strcpy(name, studentName);
        }
    protected:
        char name[40];
        int id;
    };
    

    请注意,参数char* studentNamechar studentName[40]相同,因为您不能按值传递数组作为参数,这就是编译器将其视为指向数组中第一个charchar*的原因。

您不能隐式复制数组,它们只是没有这个特性。你可以这样做:

最好的选择是在std::string而不是char[]中安全地使用名称。这将像您的示例一样工作,但可以处理任意长度的名称。

另一个选择是std::array<char, 40>。这与您现在使用的char[]几乎相同,但具有可复制的优点。它也可以与您展示的代码一起工作。与string选项不同,这将是可复制的,例如,您可以将其作为二进制数据发送和接收。

如果您真的想要或需要使用char[],您需要复制字符串"by hand":

Student::Student(int studentID ,char studentName[40]) : id(studentID){
    std::strcpy(name, studentName);
}