【问题标题】:function overloading with derived class派生类的函数重载
【发布时间】:2019-09-20 06:43:31
【问题描述】:

我有以下示例。请注意,这只是说明问题的示例。实际情况要复杂得多。

问题是我必须重载 base 类的函数。如果计算中使用的对象是 base 类型,则它使用变量 x,这对于基类和派生类都是通用的。如果对象属于 派生 类,则它使用其特定的变量 y。所以真正的问题是如何在定义类基之前定义派生类。

我知道该问题的两种解决方法,但都不是解决方案:

  • 使类派生基本类和继承的松散好处
  • 将函数计算更改为calculate(double y) {return x+y;) 什么意思像解决方案但不是由于问题很复杂。只是我需要访问对象的其余部分。
class base {
protected:
    double x;
public:
    double calculate(base b) {return x+b.x;}
    double calculate(derived d) {return x+d.y;}

}

class derived: base {
public:
    double y;

这个问题可以解决吗?

提前谢谢...

【问题讨论】:

  • 你应该使用虚函数而不是重载。您正在寻找错误的解决方案。
  • 基类知道其任何派生类是您应该重新设计的重要指标。

标签: c++ oop inheritance overloading


【解决方案1】:

转发声明derived,然后在derived 的定义之后定义calculate 的主体应该可以工作:

class derived;

class base {
protected:
    double x;
public:
    double calculate(base b);
    double calculate(derived d);    
}

class derived: base {
public:
    double y;
};

inline double base::calculate(base b) {return x+b.x;}
inline double base::calculate(derived d) {return x+d.y;}

正如其他人所说,这可能是一个糟糕的设计,base 需要了解derived。或许calculate 作为免费功能会更好:

class base {
public:
    double x;    
}

class derived: base {
public:
    double y;
};

inline double calculate(base a, base b) {return a.x+b.x;}
inline double calculate(base a, derived b) {return a.x+b.y;}

我已将x 公开以简化示例,您可以创建一个朋友(这将再次需要了解base 中的derived 类)或一个访问器函数(如果您不想要) x 公开。

第三个更惯用的选项是添加一个虚拟方法来获取每个类所需的值:

class base {
protected:
    double x;
    virtual double getValue() const { return x; }
public:
    double calculate(const base& b) { return x + b.getValue(); }
}

class derived: public base {
protected:
    double getValue() override const { return y; }     
private:
    double y;
};

请注意,calculate 必须通过引用获取类以避免对象切片(并且更有效)。

根据您的要求,计算可能会更好地实现为:

double calculate(const base& b) { return getValue() + b.getValue(); }

这意味着base.calculate(derived) 将返回与derived.calculate(base) 相同的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2011-09-05
    • 2011-03-13
    • 2021-03-19
    相关资源
    最近更新 更多