首页 > 解决方案 > 构造函数不接受 char *

问题描述

没有参数的构造函数工作,但另一个没有。我很绝望,我什么都试过了

// 标题

 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");

}

我应该改变什么?

标签: c++arraysconstructorcharinitialization

解决方案


要将文字字符串传递给函数,它必须具有类型的参数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);

推荐阅读