代码-A
/*
#include<iostream>//无虚函数
#include<string>
using namespace std;
class Zhu
{
public:
Zhu(string a, int b, float c) :name(a), age(b), score(c) {}
void display();
~Zhu();
protected:float score;
string name;
int age;
};
Zhu::~Zhu()
{
cout << "析构函数到此一游" << endl; cin.get();
}
void Zhu::display()
{
cout << "name:" << name << endl << "age:" << age << endl
<< "score:" << score << endl;
}
class Jia :public Zhu
{
public:
Jia(string a, int b, float c, string d, int e) :Zhu(a, b, c), minname(d), agoage(e) {}
void display();
~Jia();
private:
string minname;
int agoage;
};
void Jia::display()
{
cout << "name:"<<name << endl <<"age:"<<age << endl
<< "score:" <<score<< endl <<"minname:"<<minname<< endl
<< "agoage:" <<agoage<< endl;
}
Jia::~Jia()
{
cout << "来了又来" << endl;
}
int main()
{
Zhu first("张三", 19, 99.9);
Jia second("奥特曼", 9999, 100, "打怪兽", 7);
Zhu *p = &first;
p->display();
cout << endl;
p = &second; //自动进行指针类型转换,将派生类的对象的指针先转换为基类的指针,
p->display(); //基类指针指向的就是派生类的基类部分
return 0;
}
*/
/*
#include<iostream>//有虚函数
#include<string>
using namespace std;
class Zhu
{
public:
Zhu(string a, int b, float c) :name(a), age(b), score(c) {}
virtual void display();
~Zhu();
protected:float score;
string name;
int age;
};
Zhu::~Zhu()
{
cout << "析构函数到此一游" << endl; cin.get();
}
void Zhu::display()
{
cout << "name:" << name << endl << "age:" << age << endl
<< "score:" << score << endl;
}
class Jia :public Zhu
{
public:
Jia(string a, int b, float c, string d, int e) :Zhu(a, b, c), minname(d), agoage(e) {}
void display();
~Jia();
private:
string minname;
int agoage;
};
void Jia::display()
{
cout << "name:" << name << endl << "age:" << age << endl
<< "score:" << score << endl << "minname:" << minname << endl
<< "agoage:" << agoage << endl;
}
Jia::~Jia()
{
cout << "来了又来" << endl;
}
int main()
{
Zhu first("张三", 19, 99.9);
Jia second("奥特曼", 9999, 100, "打怪兽", 7);
Zhu *p = &first;
p->display();
cout << endl;
p = &second; //虚函数打破了无法通过基类指针去调用派生类对象中的成员函数
p->display(); //的限制,此时派生类同名成员函数取代了基类的中的虚函数
return 0;
}
*/
/*
#include<iostream>
using namespace std;
class Zhu{
public:Zhu() {}
~Zhu() { cout << "我是基类的析构函数" << endl; cin.get(); }
};
class Jia:public Zhu {
public:Jia() {}
~Jia() { cout << "我是派生类的析构函数" << endl; }
};
int main()
{
Zhu *p = new Jia();//用Jia类构造函数初始化Zhu类的,并用new开辟动态存储空间
delete p;//释放动态存储空间
return 0; //只有基类析构函数被调用,不执行派生类析构函数
}
*/
#include<iostream>
using namespace std;
class Zhu {
public:Zhu() {}
virtual~Zhu() //虚析构函数,该类所派生的所有派生类的析构函数也都自动成为虚析构函数
{ cout << "我是基类的析构函数" << endl; cin.get(); }
};
class Jia :public Zhu {
public:Jia() {}
~Jia() { cout << "我是派生类的析构函数" << endl; }
};
int main()
{
Zhu *p = new Jia();//用Jia类构造函数初始化Zhu类的,并用new开辟动态存储空间
delete p;//释放动态存储空间,用了指向派生类对象的基类指针,系统会调用派生类的析构函数
return 0; //基类和派生类析构函数都被调用
}
End
~
记录留存