在C 中构造函数中初始化C阵列的错误

error in initializing the c-array in the constructor in c++

本文关键字:错误 阵列 构造函数 初始化      更新时间:2023-10-16

这是我的代码,我在初始化构造函数中的char数组时会遇到错误。我还试图用字符串初始化它,但全都徒劳无功。良好的帮助将不胜感激。

#include <iostream>
using namespace std;
class employe
{
    char name[30];
    int id;
public:
    employe(int a, char b[30] ) :id(a), name(b)
    {
    }
    char getid()
    {
        return name;
    }
};

问题是,当数组传递给函数(构造函数只是一个函数)时,它将 decay 到指向其第一个元素的指针。

这意味着构造函数中的参数b确实是 pointer (键入 char*),并且您无法初始化指针的数组。

最简单的解决方案是从指针复制到构造函数内部的数组:

// Copy the string from b to name
// Don't copy out of bounds of name, and don't copy more than the string in b contains (plus terminator)
std::copy_n(b, std::min(strlen(b) + 1, sizeof name), name);

a 更好解决方案是将std::string用于字符串,然后您可以像现在尝试尝试一样初始化。