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

问题描述 投票:0回答:1

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

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

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

c++ oop linker-errors
1个回答
2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.