析构函数问题?
//v.h#include <iostream>
using namespace std;
#include<string.h>
class Person //基类:Person
{
protected:
char *name;
public:
Person(char *n) //构造函数
{
name=new char[strlen(n)+1];
strcpy(name,n);
cout<<"调用Person构造函数."<<endl;
}
virtual ~Person() { //虚析构函数
delete[]name;
cout<<"调用Person析构函数."<<endl;
}
virtual void display() //虚函数
{
cout<<"姓名:"<<name<<endl;
}
};
class Student:public Person //派生类:Student
{
protected:
char *major;
public:
Student(char *n,char *m):Person(n) //派生类的构造函数
{
major=new char[strlen(m)+1];
strcpy(major,m);
cout<<"调用Student构造函数."<<endl;
}
~Student() //派生类析构函数
{
delete[]major;
cout<<"调用Student析构函数."<<endl;
}
void display() //虚函数
{
Person::display();
cout<<"专业:"<<major<<endl;
}
};
//g.cpp
#include "v.h"
void main()
{
Person *p1=new Person("李清");
p1->display();
delete p1;
cout<<endl;
Person *p2=new Student("田农","环境科学");
p2->display();
delete p2;
cout<<endl;
Student *p3=new Student("丁一健","计算机科学技术");
p3->display();
delete p3;
cout<<endl;
}
析构函数不是自动调用的吗?那为什么要手动delete p1,p2,p3?那为何一手动删除p1,p2,p3会自动调用各个析构函数呢?
[ 本帖最后由 q345918550q 于 2010-4-27 10:10 编辑 ]