class Person
{
public:
Person(std::string& name,long id) : name_(name), id_(id) {}
~Person() {}
private:
std::string& name_;
long id_;
};
class Student : public Person
{
public:
Student(std::string& name, long id) : Person(name,id) {}
Student(std::string& name, long id, const std::vector<int*>& courses) : Person(name,id), courses_(courses) {}
virtual ~Student() {
std::vector<int*>::iterator it;
for (it = courses_.begin(); it != courses_.end(); ++it)
delete (*it);
}
const std::vector<int*>& getCourses() const { return courses_; }
private:
std::vector<int*> courses_;
};
int main(){
std::string name("Rina");
std::vector<int*> courses;
courses.push_back(new int(1345));
Person* p = new Student(name,37,courses);
Student* s = (Student*)p;
std::cout << (*(s->getCourses().at(0)));
delete p;
}
据我了解
delete p;
让我们意识到问题
~Person()
不是虚拟的。我的问题是:为什么要
~Person()
是虚拟的?