1. 程式人生 > >c++為什麼解構函式要寫成虛擬函式

c++為什麼解構函式要寫成虛擬函式

//base_derive.cpp
#include <iostream>
#include <memory>

using namespace std;

class Base{
public:
	Base(){cout << "Base" << endl;}
	~Base(){cout << "~Base" << endl;}
};

class Derive:public Base{
public:
	Derive(){cout << "Derive" << endl;}
	~Derive
(){cout << "~Derive" << endl;} }; int main() { Derive *base_ptr = new Derive; shared_ptr<Base> ptr = shared_ptr<Base>(base_ptr); cout << "hello world!" << std::endl; return 0; }

===============

//base_derive2.cpp
#include <iostream>
#include <memory>
using namespace std; class Base{ public: Base(){cout << "Base" << endl;} ~Base(){cout << "~Base" << endl;} }; class Derive:public Base{ public: Derive(){cout << "Derive" << endl;} ~Derive(){cout << "~Derive" << endl;} }; int main() { auto *base_ptr =
new Derive; auto ptr = reinterpret_cast<Base*>(base_ptr); cout << "hello world!" << std::endl; delete ptr; return 0; }

===========

//base_derive3.cpp
#include <iostream>
#include <memory>

using namespace std;

class Base{
public:
	Base(){cout << "Base" << endl;}
	virtual ~Base(){cout << "~Base" << endl;}
};

class Derive:public Base{
public:
	Derive(){cout << "Derive" << endl;}
	virtual ~Derive(){cout << "~Derive" << endl;}
};

int main()
{
	auto *base_ptr = new Derive;
	auto ptr = reinterpret_cast<Base*>(base_ptr); 
	cout << "hello world!" << std::endl;
	delete ptr;
	return 0;
}

============

//base_derive4.cpp
#include <iostream>
#include <memory>

using namespace std;

class Base{
public:
	Base(){cout << "Base" << endl;}
	virtual ~Base(){cout << "~Base" << endl;}
};

class Derive:public Base{
public:
	Derive(){cout << "Derive" << endl;}
	~Derive(){cout << "~Derive" << endl;}
};

int main()
{
	auto *base_ptr = new Derive;
	auto ptr = reinterpret_cast<Base*>(base_ptr); 
	cout << "hello world!" << std::endl;
	delete ptr;
	return 0;
}

==================

//base_derive5.cpp
#include <iostream>
#include <memory>

using namespace std;

class Base{
public:
	Base(){cout << "Base" << endl;}
	~Base(){cout << "~Base" << endl;}
};

class Derive:public Base{
public:
	Derive(){cout << "Derive" << endl;}
	~Derive(){cout << "~Derive" << endl;}
};

int main()
{
	Derive *base_ptr = new Derive;
	shared_ptr<Base> ptr = shared_ptr<Base>((Base*)base_ptr);
	cout << "hello world!" << std::endl;
	return 0;
}