避免在C 中重复代码

avoid code duplication in C++

本文关键字:代码      更新时间:2023-10-16

我在一个项目中有类似的东西:

device::getInfo()
{
    // call static instance of computer
    desktop::instance().getDetailedInfo()
    // do some work
}

我想从此类中继承并在另一个项目中重复使用代码,但我想使用其他对象实例

device::getInfo()
{
    // call static instance of computer
    laptop::instance().getDetailedInfo()
    // do some work
}

实现这一目标的最佳方法是什么?我唯一能想到的是使用预处理器指令。

我想从此类中继承并重用其他项目中的代码

...

实现这一目标的最佳方法是什么?我唯一能想到的是使用预处理器指令。

解决方案1

在派生类中覆盖device::getInfo()

device_inherited::getInfo()
{
   laptop::instance().getDetailedInfo()
}

解决方案2

如果desktoplaptop可以从普通基类派生,则可以在device中使用virtual函数来获取对适当类的参考。

device::getInfo()
{
    get_destop_base().getDetailedInfo()
}
// virtual member function
desktop_base& device::get_desktop_base()
{
   return desktop::instance();
}

// virtual member function
desktop_base& device_inherited::get_desktop_base()
{
   return laptop::instance();
}