在c ++中初始化构造函数中的c数组时出错

问题描述 投票:0回答:1

这是我的代码我在构造函数中初始化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;
    }

};
c++ string constructor initializer-list
1个回答
1
投票

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

这意味着构造函数中的参数b实际上是一个指针(类型为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);

更好的解决方案是使用std::string作为字符串,然后您可以像现在尝试一样进行初始化。

© www.soinside.com 2019 - 2024. All rights reserved.