没有参数的构造函数可以工作,而另一个则不能。 我非常绝望,我尝试了一切
//标头
class Etudiant
{
private:
char * name;
unsigned int age;
Date *datenaissance;
public:
Etudiant();
Etudiant(char * c,unsigned int,Date&);
~Etudiant();
};
这是我的.cpp
Etudiant::Etudiant()
{
this->name = new char();
strcpy(name, "kabil");
this->age = 18;
this->datenaissance = new Date();
}
Etudiant::Etudiant(char * c, unsigned int a, Date &d)
{
this->name = new char();
strcpy(this->name,c);
this->age = a;
this->datenaissance = new Date(d);
}
Etudiant::~Etudiant()
{
delete[]name;
name = 0;
}
这是我的主要
int main()
{
Date d();
Etudiant E(),E1("student",15,d);
system("pause");
}
我应该改变什么?
答案 0 :(得分:1)
要将文字字符串传递给函数,它必须具有类型char const *
而不是char *
的参数。因此,您的构造函数应具有以下原型:
Etudiant(char const * c, unsigned int, Date &);
如上所述,您也没有分配足够的内存来在构造函数中复制字符串。这行:
this->name = new char();
应该是:
this->name = new char[strlen(c) + 1];
因此您有足够的内存来执行此复制操作:
strcpy(this->name, c);