gpt4 book ai didi

c++ - 是否可以通过在基类中添加新的虚函数来破坏代码?

转载 作者:太空狗 更新时间:2023-10-29 19:41:32 25 4
gpt4 key购买 nike

是否可以通过简单地向基类添加一个新的虚函数来改变观察到的程序行为?我的意思是不必对代码进行其他更改。

最佳答案

以下程序打印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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com