虚析构函数(派生类与基类)

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;
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值