繁体   English   中英

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

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

从虚拟析构函数调用虚拟 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;
}

为什么? 我也尝试对此进行编辑析构函数:

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

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

现在代码正在编译,但在析构函数中我得到纯虚拟 function 调用。 我该如何解决?

当你调用Animal析构函数时,派生的 class ( Dog / Cat ) 已经调用了它的析构函数,因此它是无效的。 调用Dog::sound()会冒访问被破坏数据的风险。

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

暂无
暂无

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

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