gpt4 book ai didi

c++ - 调试断言失败字符串!=NULL C++

转载 作者:行者123 更新时间:2023-11-28 06:15:05 25 4
gpt4 key购买 nike

我创建了一个类 patient,其中包含有关患者的一些信息,例如姓名、年龄、地址等。

当我尝试编译程序时,我得到了一个Debug Assertion Failed (Expression String != NULL) 我似乎找不到为什么会这样。

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>
using namespace std;

class pacient{
protected:
int colesterol;
int tensiune_arteriala;
char * nume;
char * prenume;
int varsta;
char * adresa;
char * data_analiza;
public:
//constructor cu toti parametrii
pacient(){};
pacient(int colesterol, int tensiune_art, char * nume, char *prenume,
int varsta, char * adresa, char *data_analiza)
{
(*this).colesterol = colesterol;
tensiune_arteriala = tensiune_art;
strcpy((*this).nume, nume);
strcpy((*this).prenume, prenume);
(*this).varsta = varsta;
strcpy((*this).adresa, adresa);
strcpy((*this).data_analiza, data_analiza);
}
//destructor
~pacient(){
colesterol = 0;
tensiune_arteriala = 0;
strcpy(nume, "");
strcpy(prenume, "");
varsta = 0;
strcpy(adresa, "");
strcpy(data_analiza, "");
}
//functie virtuala
virtual char * get_name() { return "Este pacient"; }

//citirea si afisarea obiectelor
friend istream &operator>> (istream&in, pacient&ob);
friend ostream &operator<< (ostream&out, const pacient&ob);

};

istream& operator>>(istream &in, pacient &ob){
cout << "Nume: "; gets(ob.nume); cout << endl;
cout << "Prenume: "; gets(ob.prenume); cout << endl;
cout << "Varsta: "; cin >> ob.varsta; cout << endl;
cout << "Adresa: "; gets(ob.adresa); cout << endl;
cout << "Data analiza: "; gets(ob.data_analiza); cout << endl;
cout << "Colesterol: "; cin>>ob.colesterol; cout << endl;
cout << "Tensiune arteriala: "; cin>>ob.tensiune_arteriala; cout << endl;
return in;
}

ostream &operator<< (ostream&out, const pacient&ob){
cout << "Nume: "; puts(ob.nume); cout << endl;
cout << "Prenume: "; puts(ob.prenume); cout << endl;
cout << "Varsta: "; cout << ob.varsta; cout << endl;
cout << "Adresa: "; puts(ob.adresa); cout << endl;
cout << "Data analiza: "; puts(ob.data_analiza); cout << endl;
cout << "Colesterol: "; cout << ob.colesterol; cout << endl;
cout << "Tensiune arteriala: "; cout << ob.tensiune_arteriala; cout << endl;
return out;
}

int main()
{
pacient a;
cin >> a;
cout << a;
}

最佳答案

那是因为你的成员是指针:

  char * nume;
char * prenume;
...

但是你没有初始化它们,也没有分配内存,但仍然尝试使用它们:

    pacient(int colesterol, int tensiune_art, char * nume, char *prenume,
int varsta, char * adresa, char *data_analiza)
{
...
strcpy((*this).nume, nume); ///<======= OUCH !!!!

考虑使用 string 而不是 char*:

  • 您不必管理内存,它是自动的
  • 你可以使用=代替strcpy
  • 您可以返回字符串而不必担心内存泄漏

关于c++ - 调试断言失败字符串!=NULL C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30470082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com