我创建了一名班级病人,其中包含有关患者的一些信息,如姓名,年龄,地址等。
当我尝试编译程序时,我得到了一个 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;
}
答案 0 :(得分:1)
那是因为你有成员指针:
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