构造函数值意外地改变c ++

时间:2014-12-07 19:01:51

标签: c++ constructor int copy-constructor

我有一个Students课程来存储names, ages, gender, subjects, highestmark, lowestmark

基本上,我有一个reset()函数,它将所有内容设置为null,看起来像这样

char names[10];
char names[10];
char names[10];
int ages;
int highestMark;
int lowestMark;

void Students::reset()
{
  strncpy(names, "NULL", sizeof(names));
  names[9] = '\0';
  ages = 0;
  highestMark = 0;
  lowestMark = 0;
  strncpy(gender, "NULL", sizeof(gender);
  gender[9] = '\0';
  strncpy(subjects, "NULL", sizeof(subjects));
  subjects[9] = '\0';
}

我的构造函数看起来像这样......

Students::Students()
{
  reset();
}

复制构造函数看起来像这样......

Students::Students(const Students& student)
{
   reset();
   cout << highestMark << endl; // PRINTS 107894124
   cout << lowestMark << endl;  // PRINTS 541203654
   cout << ages << endl; // PRINTS RANDOM VALUES
   cout << subjects << endl;
   cout << names << endl;
}

highestMarklowestMark未返回0,而是返回107894124541203654等随机值

为什么不按预期返回0

1 个答案:

答案 0 :(得分:1)

strcpy(something, NULL)是未定义的行为,因此任何事情都可能发生。您最有可能通过调用strcpy来覆盖您的数据。你想要的可能是

strcpy(names, "");

但是如果你只使用std::string而不是原始字符数组会更好。