0
我想在默認構造函數中設置一個等於null('\ 0')的char數組。我試圖設置一個已經初始化的字符指針(該類的受保護成員)的值爲空,當沒有參數傳遞。如果有正確的參數傳遞,該程序完美工作,但是當我將它們設置爲默認構造函數時,出現分段錯誤:11錯誤。如何在默認構造函數中將char數組初始化爲null?
這是頭文件:
#ifndef _DVD_H_
#define _DVD_H_
class DVD {
protected:
unsigned int id;
char* title;
char* director;
char* makecopy(const char*);
public:
DVD(unsigned int i, const char* t, const char* dir);
void display();
DVD()
{
const char temp[] = {'\0'};
id = 0;
title = makecopy(temp);
director = makecopy(temp);
}
};
#endif /* _DVD_H_ */
,這是.cpp文件:
#include <iostream>
#include "DVD.h"
using namespace std;
DVD::DVD (unsigned int i, const char* t, const char* dir)
{
//Constructing id
id = i;
//Constructing title
title = makecopy(t);
//Constructing director
director = makecopy(dir);
}
void DVD::display()
{
//Creating variables to track the length of the title/director and the location of the space.
int len_t,len_dir,space_dir;
for (len_t = 0; title[len_t] != '\0'; len_t++)
;
for (len_dir = 0; director[len_dir] != '\0'; len_dir++)
;
for (space_dir = 0; director[space_dir] != ' '; space_dir++)
;
//Display the information in the desired format.
cout << '[' << id << ". " << title << '/';
for (int p = 0; p < space_dir; p++)
cout << director[p];
for (int j = space_dir; j < len_dir; j++)
cout << director[j];
cout << ']' << endl;
}
char* DVD::makecopy(const char* str)
{
int len;
char* copy;
for (len = 0; str[len] != '\0'; len++)
;
copy = new char[len+1];
for (int i = 0; i < len+1; i++)
copy[i] = str[i];
return copy;
}
,這是其他.cpp文件
#include<iostream>
using namespace std;
#include"DVD.h"
int main()
{
char str[] = "Gandhi";
DVD d1(4, str, "Richard Attenborough");
DVD d2;
cout << "First step: " << endl;
cout << "After constructors:" << endl;
d1.display(); cout << endl; // [4. Gandhi/Richard Attenborough]
d2.display(); cout << endl; // [0. /]
cout << "Test for dynamically allocated copies" << endl;
d1.display(); cout << endl; // [4. Gandhi/Richard Attenborough]
d2.display(); cout << endl; // [0. /]
}
使用'的std :: string'代替。 – NathanOliver
如果不是這樣,那麼至少使用'strdup()'而不是手動'makecopy()'。或者至少使用'strlen()'和'strcpy()'而不是手動循環。 –
我的任務是使用空字符串數組而不是字符串。這是否阻止我能夠使用這些?另外,makecopy()也是賦值的一部分。 –