c++ - 构造函数不接受 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");
}
我应该改变什么?
解决方案
要将文字字符串传递给函数,它必须具有类型的参数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);
推荐阅读
- error-handling - 当某些线程恐慌时,如何立即退出整个多线程 Rust 程序程序?
- javascript - 在引导模式窗口之外选择下拉选择会导致模式关闭
- sql-server - Oracle CASE WHEN 'null' 与 Int 一起用于 SSRS 报告
- html - 如何确保菜单关闭时立即消失,而不是部分消失?
- azure - All Azure WebJob possible statuses
- javascript - 当div在屏幕上时如何运行JS函数?
- java - 在 IntelliJ 中调试 spring 依赖项
- c# - 即使使用 baseUrl,SelectPdf ConvertHtmlString 也不显示图片
- javascript - 对 *SPECIFIC* 道具更改的反应调用方法
- html - 如何正确设置 CSP 以允许在我自己的域上使用 iframe?