是否可以通过简单地向基类添加一个新的虚函数来改变观察到的程序行为?我的意思是不必对代码进行其他更改。
最佳答案
以下程序打印OK。取消注释 B
中的虚函数,它将开始打印 CRASH!。
#include <iostream>
struct B
{
//virtual void bar() {}
};
struct D : B
{
void foo() { bar(); }
void bar() { std::cout << "OK" << std::endl; }
};
struct DD : D
{
void bar() { std::cout << "CRASH!" << std::endl; }
};
int main()
{
DD d;
d.foo();
return 0;
}
问题是,在引入虚函数B::bar()
后,D::foo 中对
从静态变为动态。 bar()
的调用绑定(bind)()
关于c++ - 是否可以通过在基类中添加新的虚函数来破坏代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38657534/