繁体   English   中英

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

[英]How to initialize an array in the member initializer list

使用C ++的完整初学者。

这是成员初始化列表:

Student.cpp

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

Student.h

class Student{

protected:
    char name[40];
    int id;
}

我的问题是name的类型为char[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* studentName是相同的char studentName[40]因为你不能按值传递数组作为参数,这就是为什么编译器只是将其视为一个char*指向第一char在数组中。

您不能隐式复制数组,它们只是没有此功能。 您可以改用以下方法:

最好的选择是使用std::string代替char[]来保证名称安全。 这将像您的示例一样工作,但是可以处理任意长度的名称。

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

如果您确实需要或需要使用char[] ,则需要“手工”复制字符串:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM