从虚拟析构函数错误C调用虚拟函数

时间:2020-04-03 11:40:16

标签: c++ oop linker-errors

从虚拟析构函数调用虚拟函数时,出现无法解析的外部符号。

#include <iostream>

class Animal {
public:
  virtual void Sound() = 0;

  virtual ~Animal() {
    this->Sound();
  }
};

class Dog : public Animal {
public:
  void Sound() override {
    printf("Woof!\n");
  }
};

class Cat : public Animal {
public:
  void Sound() override {
    printf("Meow!\n");
  }
};

int main() {
  Animal* dog = new Dog();
  Animal* cat = new Cat();

  dog->Sound();
  cat->Sound();

  delete dog;
  delete cat;

  system("pause");
  return 0;
}

为什么? 我也尝试过编辑析构函数:

  void Action() {
    this->Sound();
  }

  virtual ~Animal() {
    this->Action();
  }

现在代码正在编译,但是在析构函数中,我得到了纯虚函数调用。 我该怎么解决?

1 个答案:

答案 0 :(得分:2)

在调用Animal析构函数时,派生类(Dog / Cat)已经被调用了它的析构函数,因此它是无效的。调用Dog::sound()可能会访问被破坏的数据。

因此,不允许析构函数调用访问派生的类方法。它尝试访问Animal::sound(),但它是纯虚拟的-因此会出错。

相关问题