/*** @file interesting_facts4.cpp* @brief 抽象類可以有構造函數* @author 光城* @version v1* @date 2019-07-20*/#include<iostream>
using namespace std; // An abstract class with constructor
class Base
{ protected: int x; public: virtual void fun()=0; Base(int i){ x = i;}}; class Derived: public Base
{ int y; public: Derived(int i, int j):Base(i){ y = j;} void fun(){ cout <<"x = "<< x <<", y = "<< y;}}; int main(void){ Derived d(4, 5); d.fun();return0;}
構造函數不能是虛函數,而析構函數可以是虛析構函數
/*** @file interesting_facts5.cpp* @brief 構造函數不能是虛函數,而析構函數可以是虛析構函數。* 例如:當基類指針指向派生類對象并刪除對象時,我們可能希望調用適當的析構函數。如果析構函數不是虛擬的,則只能調用基類析構函數。* @author 光城* @version v1* @date 2019-07-20*/
#include<iostream>
using namespace std;class Base {public:Base(){ cout <<"Constructor: Base"<< endl;}virtual ~Base(){ cout <<"Destructor : Base"<< endl;}};class Derived: public Base {public:Derived(){ cout <<"Constructor: Derived"<< endl;}~Derived(){ cout <<"Destructor : Derived"<< endl;}};int main(){Base *Var = new Derived();delete Var;return0;}