0

考虑以下基类:

class Base
{
public:
    virtual ~Base(void);
    virtual void foo(void);
    virtual void bar(void) = 0;
}

现在假设我知道给定的类应该是 Base 的最派生类。我应该将函数声明为虚拟函数吗?最派生的类可以/将与 Base 多态地一起使用。

例如,我应该使用MostDerived1orMostDerived2吗?

class MostDerived1 : public Base
{
public:
    ~MostDerived1(void);
    void foo(void);
    void bar(void);
}

class MostDerived2 : public Base
{
public:
    virtual ~MostDerived2(void);
    virtual void foo(void);
    virtual void bar(void);
}

我倾向于 MostDerived1,因为它最接近地模拟了程序员的意图:我希望 MostDerived1 的另一个子类与 MostDerived1 多态地一起使用。

这个推理正确吗?除了显而易见的问题之外,我应该选择 MostDerived2 有什么好的理由there could be a >0% chance MostDerived2 should be used polymorphically with any deriving classes (class OriginalAssumptionWrong : public MostDerived2)吗?

请记住MostDerived1/MostDerived2都可以与Base.

4

3 回答 3

3

将 virtual 添加到派生类不会改变它们的行为,MostDerived并且MostDerived2具有完全相同的行为。

但是,它确实记录了您的意图。我会为此目的推荐它。假设它在您的平台上可用,该override关键字也对此有所帮助。

于 2013-07-18T23:06:22.373 回答
2

You can't turn off virtualness. Another class derived from either MostDerived1 or MostDerived2 can also override any of the virtual functions regardless of whether you omit the virtual keyword somewhere in the class hierarchy or not.

If you want to enforce that no other class derives from MostDerived1, define it as

class MostDerived1 final : public Base
{
  // ...
};

The final keyword can also be used for individual virtual member functions, ensuring no derived class overrides that specific function.

于 2013-07-18T23:09:42.197 回答
1

一旦功能在层次结构中的某处被清除为虚拟,它就永远是虚拟的。
您可以使用final,或者override如果您使用C++11

于 2013-07-18T23:06:32.540 回答