gpt4 book ai didi

c++ - 如何摆脱派生类中的重复代码?

转载 作者:行者123 更新时间:2023-11-30 02:38:34 24 4
gpt4 key购买 nike

我有一个像这样的类层次结构:

class A {    
list<A*> children;
public:
void update() {
do_something();
update_current();
for(auto child : children)
children->update();
}
protected:
virtual void update_current() {};
};

class B : public A {
protected:
void update_current() override {
do_something_important();
};
};

class C1 : public B {
protected:
void update_current() override {
B::update_current();
do_something_very_important();
};
};

class C2 : public B {
protected:
void update_current() override {
B::update_current();
do_something_very_important_2();
};
};

int main() {
A* a = new A();
//fill a's childred list somehow
while(come_condition) {
//some code
a.update();
//something else
}
return 0;
}

问题是:如何在不改变程序行为的情况下从派生类中删除重复的 B::update_current(); 调用?除了手动调用基类函数外,是否有可能或没有解决方案?谢谢。

最佳答案

你可以让 B 的 child 重写一个不同的函数:

class B : public A {
protected:
void update_current() override final {
do_something_important();
do_something_important_later();
};

virtual void do_something_important_later() = 0;
};

与:

class C2 : public B {
protected:
void do_something_important_later() override {
do_something_very_important_2();
};
};

关于c++ - 如何摆脱派生类中的重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30715418/

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