gpt4 book ai didi

c++ - C++ 继承的最佳实践

转载 作者:行者123 更新时间:2023-12-03 17:50:08 25 4
gpt4 key购买 nike

如果我想使用继承来避免重复 common_method下面的方法

int A::different_method()
{ return 1; }

int A::common_method()
{ return this->different_method()+1; }

int B::different_method()
{ return 2; }

int B::common_method()
{ return this->different_method()+1; }

最好的方法是什么?

一种方法是制作 AB从基类继承 C ,使用新方法:
int A::different_method()
{ return 1; }

int B::different_method()
{ return 2; }

int C::different_method()
{ return 0; }

int C::common_method()
{ return this->different_method()+1; }

但有点烦人的是我还必须定义无用的 C::different_method .这种情况的最佳做法是什么?

最佳答案

尝试使用 pure virtual function :

struct Base {
virtual int different_method() = 0;

int common_method() {
return different_method() + 1;
}
};

struct Derived1 : Base {
int different_method() override {
return 1;
}
};

struct Derived2 : Base {
int different_method() override {
return 2;
}
};

看看 live

关于c++ - C++ 继承的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60000760/

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