从虚析构函数错误C++调用虚函数
Calling virtual function from virtual destructor error C++
从虚析构函数调用虚函数时,我得到无法解析的外部符号。
#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();
}
现在代码正在编译,但在析构函数中我得到了纯虚函数调用。
我该如何解决?
当您调用 Animal
析构函数时,派生的 class (Dog
/Cat
) 已经调用了其析构函数,因此它是无效的。调用 Dog::sound()
将面临访问已损坏数据的风险。
因此不允许析构函数调用访问派生的 class 方法。它尝试访问 Animal::sound()
,但它是纯虚拟的 - 因此出现错误。
从虚析构函数调用虚函数时,我得到无法解析的外部符号。
#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();
}
现在代码正在编译,但在析构函数中我得到了纯虚函数调用。 我该如何解决?
当您调用 Animal
析构函数时,派生的 class (Dog
/Cat
) 已经调用了其析构函数,因此它是无效的。调用 Dog::sound()
将面临访问已损坏数据的风险。
因此不允许析构函数调用访问派生的 class 方法。它尝试访问 Animal::sound()
,但它是纯虚拟的 - 因此出现错误。