如何在成员初始化项列表中初始化数组
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++中赋值数组,因此基本上有两种可能性:
-
惯用的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();
-
如果你想使用
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[]
,您需要复制字符串"by hand":
Student::Student(int studentID ,char studentName[40]) : id(studentID){
std::strcpy(name, studentName);
}
相关文章:
- C++类 - 初始化列表 - 递归 - 按值传递
- 在初始化列表之外手动调用基类的构造函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- std::map与谓词与初始化列表
- 类内初始化与构造函数初始化列表的顺序
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++初始化列表与分配值
- C++初始化列表中的向量集大小或调整大小
- 在构造函数初始化列表中使用 std::variant
- emplace_back初始化列表错误,当初始化列表在独立变量上工作时
- 解释了构造函数成员初始化列表
- 使用初始化列表时如何获取私有数据?
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 如何在成员初始化列表中声明共享指针
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 我可以检查初始化列表中设置的构造函数主体中的变量吗
- 使用整数初始化列表初始化长双精度的向量
- 是否可以在C++中使用初始化列表设置数组的特定成员?