很诡异的指针问题
问题有点乱,我理一理慢慢表述下
首先是一个Person类,代码如下
#include "Date.h"
class Person
{
public:
Person(int id, int year, int month, int day);
Person(Person &); // 问题出在这个方法里
~Person();
int getId();
Date* getBirthDate(); // return the pointer of the object
private:
int id;
Date* birthDate; // The pointer of the object
};
#ifndef DATE_H
#define DATE_H
class Date{
public:
Date(int newYear, int newMonth, int newDay);
int getYear();
void setYear(int year);
private:
int year;
int month;
int day;
};
#endif
Person::Person(Person &person){
id = person.id;
Date *p = person.getBirthDate();
birthDate = new Date(*p); // 调试的时候一切正常
}
Person person1(111, 1970, 5, 3);
Person person2(222, 2000, 11, 8);
person1 = Person(person2); // Copy person2 to person1
#include <cstdio>
#ifndef DATE_H
#define DATE_H
class Date{
public:
Date(int newYear, int newMonth, int newDay) : year(newYear), month(newMonth), day(newDay){}
int getYear(){return year;}
void setYear(int newYear){year=newYear;}
private:
int year;
int month;
int day;
};
#endif
//#include "Date.h"
class Person
{
public:
Person(int id, int year, int month, int day) : id(id), birthDate(new Date(year, month, day)){}
Person(Person &person){
id = person.id;
Date *p = person.getBirthDate();
birthDate = new Date(*p); // 调试的时候一切正常
}
~Person(){delete birthDate;}
int getId(){return id;}
Date* getBirthDate(){return birthDate;}; // return the pointer of the object
Person& operator = (const Person& other)
{
Date* temp = new Date(*other.birthDate);
delete birthDate;
birthDate = temp;
id = other.id;
return *this;
}
private:
int id;
Date* birthDate; // The pointer of the object
};
int main()
{
Person person1(111, 1970, 5, 3);
Person person2(222, 2000, 11, 8);
person1 = Person(person2); // Copy person2 to person1
printf("%d\n", person1.getBirthDate()->getYear());
return 0;
}