简体   繁体   English

C ++中的抽象类

[英]abstract class in C++

I have a derived derived class from an abstract class. 我有一个抽象类的派生派生类。 The code is below. 代码如下。 I have a FishTank class which is derived from an Aquarium and Aquarium is derived from item. 我有一个FishTank类,它是从水族馆派生的,而水族馆是从项目派生的。 My question is that should I put the definition of virtual int minWidth() const = 0; 我的问题是我应该把虚拟int的定义设为minWidth()const = 0;。 in aquarium again or is the code below sufficient? 在水族馆中还是下面的代码足够?

class Item{
public:
   virtual int minWidth() const = 0;
};

class Aquarium: public Item{
public:
  virtual int calWidth() = 0;   // Pure virtual function.
};

class FishTank : public Aquarium{
    public:
       FishTank(int base1, int base2, int height);
       ~FishTank();
    int calWidth();
        int minWidth();
};

There's no reason to do it again. 没有理由再做一次。 It only serves to waste space and give you the opportunity to get compile errors from typos. 它只会浪费空间,使您有机会从错别字中获取编译错误。 :) Once you inherit, it's just like it had been there anyway. :)一旦继承,就好像它一直在那里一样。

However, you don't actually ever implement it! 但是,您实际上从未实现它! Why? 为什么? You're missing const in FishTank : 您在FishTank缺少const

int minWidth() const; // <-- const!

You don't need to re-declare minWidth ; 您无需重新声明minWidth the pure virtual function will be inherited from Item . 纯虚函数将从Item继承。

Do you mean "definition" or just a "declaration"? 您是指“定义”还是“声明”? If a suitable default definition is likely to be applicable to all Aquariums then by all means define it in the Aquarium class, but you might not want to make it pure virtual otherwise all derived classes would still have to override it even if they just wanted to call the base class implementation. 如果一个合适的默认定义可能适用于所有水族馆,则一定要在水族馆类中对其进行定义,但是您可能不希望使其成为纯虚拟的,否则所有派生类仍然不得不重写它,即使他们只是想调用基类实现。

Otherwise, there's no point in just re-declaring it. 否则,仅需重新声明就没有意义。 Either way derived concrete classes must still override the function and it makes no difference the behaviour of the function when called through a pointer or reference to either Item or Aquarium. 无论哪种方式,派生的具体类都仍必须重写该函数,并且在通过指针或对Item或Aquarium的引用进行调用时,函数的行为没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM