我是C ++的新手,所以请放轻松,我有以下课程:
class DATA
{
private:
char* Name;
char* Address;
int Id;
void initData(int size=200)
{
(this->Name)=(char*)malloc(sizeof(char)*size);
(this->Address)=(char*)malloc(sizeof(char)*size);
}
public:
void readData(void)
{
this->initData();
printf("Enter Name: "); scanf("%s\n",this->Name);
printf("Enter Address: "); scanf("%s\n",this->Address);
printf("Enter Id: "); scanf("%d\n",&(this->Name));
}
void printData(void)
{
printf("Name: %s",this->Name);
printf("Address: %s",this->Address);
printf("Id: %d",this->Id);
}
};
但是,当我初始化一个对象然后调用公共方法时,会发生以下情况:
Enter Name: John Doe
Enter Address: 53 Olive, St.
Segmentation fault (core dumped)
因此,如果有人可以告诉我原因(我知道什么是细分错误,但不明白为什么在这里)。
在方法中 readData
printf("Enter Id: "); scanf("%d\n",&(this->Name));
您应该将其读Id
为整数,但this->Name
改为读入字符串。要么
scanf("%d\n",&(this->Id));
当您使用C ++,它的方便和更容易使用cin
,并cout
比C风格scanf
和printf
运行到这些类型的问题。
cin >> Id;