1. 程式人生 > >虛解構函式(派生類與基類)

虛解構函式(派生類與基類)

1.情況1,

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

複製程式碼

class Derived1 : public Base {
 public:
  Derived1():name_(new string("NULL")) {}
  Derived1(const string& n):name_(new string(n)) {}

  ~Derived1() {
    delete name_;
    cout << "~Derived1(): name_ has been deleted." << endl;
  }

 private:
  string* name_;
};

class Derived2 : public Base {
 public:
  Derived2():name_(new string("NULL")) {}
  Derived2(const string& n):name_(new string(n)) {}

  ~Derived2() {
    delete name_;
    cout << "~Derived2(): name_ has been deleted." << endl;
  }

 private:
  string* name_;
};

複製程式碼

我們看下面對其析構情況進行測試:

int main() {
  Derived1* d1 = new Derived1();
  Derived2 d2 = Derived2("Bob");
  delete d1;
  return 0;
}

因為引用的型別就是派生類,所以解構函式,先刪除派生類,後刪除基類(建立一個派生類,一定會先建立一個基類(成員初始化列表語法)

結果:

~Derived1(): name_ has been deleted.

~Base()

~Derived2(): name_ has been deleted.

~Base()

情況二:

int main() {
  Base* base[2] = {
    new Derived1(),
    new Derived2("Bob")      
  };
  for (int i = 0; i != 2; ++i) {
    delete base[i];    
  }
  return 0;
}

沒有虛解構函式,所以刪除引用的型別

動態繫結:http://blog.csdn.net/iicy266/article/details/11906509

 

基類析構虛擬函式:因為動態繫結,先刪除析構類,後刪除基類

~Base()

~Base()

情況三:

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