简体   繁体   English

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

[英]Calling virtual function from virtual destructor error C++

I get unresolved external symbol when calling virtual function from virtual destructor.从虚拟析构函数调用虚拟 function 时,我得到未解析的外部符号。

#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;
}

Why?为什么? Also I tried edit destructor to this:我也尝试对此进行编辑析构函数:

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

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

Now code is compiling, but in destructor I get pure virtual function call.现在代码正在编译,但在析构函数中我得到纯虚拟 function 调用。 How can I solve it?我该如何解决?

By the time you call the Animal destructor, the derived class ( Dog / Cat ) has already had its destructor called, thus it is invalid.当你调用Animal析构函数时,派生的 class ( Dog / Cat ) 已经调用了它的析构函数,因此它是无效的。 Calling Dog::sound() would risk accessing destroyed data.调用Dog::sound()会冒访问被破坏数据的风险。

Thus the destructor call is not allowed to access derived class methods.因此,析构函数调用不允许访问派生的 class 方法。 It tries to access Animal::sound() , but it's pure virtual - hence the error.它尝试访问Animal::sound() ,但它是纯虚拟的 - 因此出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM