【问题标题】:error in initializing the c-array in the constructor in c++在 c++ 的构造函数中初始化 c 数组时出错
【发布时间】:2017-12-21 11:20:41
【问题描述】:

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

问题在于,当一个数组被传递给一个函数(而构造函数只是一个函数)时,它会衰减指向它的第一个元素的指针。

这意味着你的构造函数中的参数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 用于字符串,然后您可以像现在尝试那样进行初始化。

【讨论】:

  • @KashifMehmood3314-FBASBSSEF1 它有效并解决了您的问题,然后请考虑通过单击答案旁边的复选框将其标记为已接受。请花点时间阅读the help pagestake the Stack Overflow tour
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
相关资源
最近更新 更多