【问题标题】:C++ class Design with Inheritance带有继承的 C++ 类设计
【发布时间】:2021-10-30 18:26:31
【问题描述】:
class Base 
{
public:
    static int  GetType_S()
    {
        return 1;
    }
    virtual int GetType()
    {
        return GetType_S();
    }
};

class Son1 : public Base 
{
public:
    static int GetType_S()
    {
        return 2;
    }
    virtual int GetType()
    {
        return GetType_S();
    }
};

我的问题是:当我需要像“Son1,Son2...”这样的其他类时,每个类都应该实现GetType和GetType_S函数,这两个函数是重复的。那么如何优雅地设计这些类让子类实现只有一个功能?而且最好不要使用宏。

【问题讨论】:

  • 你的例子不是很清楚,有一个类持有int,然后让GetType返回int会更容易和“优雅”。你有什么具体想要实现的吗?
  • 你的问题不清楚,你应该尝试改写。至于必须实现基类函数的具体派生类,只有当父类函数是纯虚函数时才成立,例如 virtual int GetType() = 0;如果函数不是纯虚函数,并且在父函数中具有默认实现,则子函数不必重新实现。
  • @GonenI 纯虚函数使基类成为我们无法从中创建对象的抽象类。派生类必须实现纯虚函数,这是必需的,因为基类没有默认行为。但是,派生类可以选择是否实现非虚函数。

标签: c++ inheritance


【解决方案1】:

您可以拥有一个每个SonN 继承自的类模板,而后者又继承Base

template <int Type>
class Middle : public Base 
{
public:
    static int  GetType_S()
    {
        return Type;
    }
    virtual int GetType()
    {
        return GetType_S();
    }
};

class Son1 : public Middle<2> {};

class Son2 : public Middle<3> {};

class Whatever : public Middle<42> {}; 

或者,如果这些类中没有其他内容:

using Son1 = Middle<2>;
using Son2 = Middle<3>;
using Whatever = Middle<42>;

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多