具体代码如下:有空大佬帮忙指导一下。
疑惑一:当animal->Speak();调用开始的时候,调用子类(派生类)的构造函数,当这段animal->Speak();调用完,不应该调用子类的析构函数吗?为什么结果显示不调用。把父类的析构变成纯虚析构,就可以解决。
#include <iostream>
using namespace std;
class Animal
{
public:
Animal()
{
cout << "Animal 构造函数调用!" << endl;
}
virtual void Speak() = 0;
~Animal()
{
cout << "Animal 纯虚析构函数调用!" << endl;
}
//virtual ~Animal() = 0;
};
//Animal::~Animal()
//{
//cout << "Animal 纯虚析构函数调用!" << endl;
//}
class Cat : public Animal
{
public:
Cat(string name)
{
cout << "Cat构造函数调用!" << endl;
m_Name = new string(name);
}
virtual void Speak()
{
cout << *m_Name << "小猫在说话!" << endl;
}
~Cat()
{
cout << "Cat析构函数调用!" << endl;
if (this->m_Name != NULL) {
delete m_Name;
m_Name = NULL;
}
}
public:
string* m_Name;
};
void test01()
{
Animal* animal = new Cat("Tom");
animal->Speak();
delete animal;
}
int main() {
test01();
system("pause");
return 0;
}
疑惑一:当animal->Speak();调用开始的时候,调用子类(派生类)的构造函数,当这段animal->Speak();调用完,不应该调用子类的析构函数吗?为什么结果显示不调用。把父类的析构变成纯虚析构,就可以解决。
#include <iostream>
using namespace std;
class Animal
{
public:
Animal()
{
cout << "Animal 构造函数调用!" << endl;
}
virtual void Speak() = 0;
~Animal()
{
cout << "Animal 纯虚析构函数调用!" << endl;
}
//virtual ~Animal() = 0;
};
//Animal::~Animal()
//{
//cout << "Animal 纯虚析构函数调用!" << endl;
//}
class Cat : public Animal
{
public:
Cat(string name)
{
cout << "Cat构造函数调用!" << endl;
m_Name = new string(name);
}
virtual void Speak()
{
cout << *m_Name << "小猫在说话!" << endl;
}
~Cat()
{
cout << "Cat析构函数调用!" << endl;
if (this->m_Name != NULL) {
delete m_Name;
m_Name = NULL;
}
}
public:
string* m_Name;
};
void test01()
{
Animal* animal = new Cat("Tom");
animal->Speak();
delete animal;
}
int main() {
test01();
system("pause");
return 0;
}