Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตัวทำลายเสมือนบริสุทธิ์ใน C ++


ตัวทำลายเสมือนล้วนเป็นไปได้ใน C ++ หากคลาสมี pure virtual destructor จะต้องจัดเตรียมเนื้อหาฟังก์ชันสำหรับ destructor เสมือนแท้

โค้ดตัวอย่าง

#include <iostream>
using namespace std;

class B {
   public:
   virtual ~B()=0; // Pure virtual destructor
};

B::~B() {
   std::cout << "Pure virtual destructor is called";
}

class D : public B {
   public:
   ~D() {
      cout << "~D() is executed"<<endl;
   }
};

int main() {
   B *bptr=new D();
   delete bptr;
   return 0;
}

ผลลัพธ์

~D() is executed
Pure virtual destructor is called