C++析构函数继承

Ali*_*Ali 2 c++ inheritance destructor

/* Problem 50 */
#include <iostream>
using namespace std;

class a {
    char ach;
  public:
    a(char c) { ach = c - 1; }
    ~a(); // defined below
    virtual void out(ostream &os) {
      if ('m' < ach)
        os << ach << char(ach+7) << char(ach+6) << ' ';
      else
        os << ach << ach << ach;
    }
};

class b: public a {
    char bach;
  public:
    b(char c1, char c2) : a(c1) { bach = c2-1; }
    void out(ostream &os) {
      a::out(os);
      os << ' ' << bach << char(bach + 11);
    }
};

ostream &operator<<(ostream &os, a &x) {
  x.out(os);
  return os;
}

a::~a() {
  cout << *this; // calls above operator
}

int main() {
  b var1('n', 'e');
  a var2('o');
  cout << "Homer says: " << var1 << '\n';
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我混淆了为什么只有两个对象被破坏而有三个对象被构造

我也在上面cout构建了每个构造,base_class并且derived_class看看有多少是构造的,我对构造对象的数量是正确的,但是当我做破坏时我错了.

如果有人可以请指出为什么最后的破坏不适用于正在创建的第一个对象?

Nav*_*een 6

只构造了两个对象,你在构造函数中看到的3个couts是因为当你创建一个派生类对象时,会调用基类构造函数.作为旁注,您需要将class a析构函数声明为虚拟.