简体   繁体   English

C ++多态样式-仅在子类中实现自定义方法

[英]C++ polymorphism style - implement custom methods in subclass only

I'm wondering whether this implementation of polymorphism is desirable in C++. 我想知道在C ++中是否需要这种多态实现。

I have a superclass (cPolygon) and two subclasses (cRectangle and cTriangle). 我有一个超类(cPolygon)和两个子类(cRectangle和cTriangle)。 The question is whether it's considered good form to implement a method in one of the subclasses that is not included in the superclass ie. 问题是,在超类即未包含的子类之一中实现方法是否被认为是一种好的形式。 should I be creating the setSomething method only in cRectangle? 我应该只在cRectangle中创建setSomething方法吗? If I do so, should I also create this method in the superclass cPolygon as well (obviously not abstract though)? 如果这样做,是否还应该在超类cPolygon中创建此方法(虽然显然不是抽象的)?

Thanks guys Pete 谢谢你们皮特

#include <iostream>
using namespace std;

// Super class
class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
  };
// Sublcass Rectangle
class CRectangle: public CPolygon {
  public:
    int area ()
      { return (width * height); }
    // Method only present in rectangle.
        // Is this OK?
    void setSomething(int a) {
        _a = a;
    }
private:
    int _a;
  };


// Subclass Triangle
class CTriangle: public CPolygon {
  public:
    int area ()
      { return (width * height / 2); }
  };

int main () {
  CRectangle rect;
  CTriangle trgl;
  CPolygon * ppoly1 = &rect;
  CPolygon * ppoly2 = &trgl;
  // Is this OK?
  rect->setSomething(3);
  trgl->set_values(2,3);

  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  cout << rect.area() << endl;
  cout << trgl.area() << endl;
  return 0;
}

It is possible and completely valid to have new methods in the subclass which are not available in the super class. 在子类中具有超类中不可用的新方法是可能且完全有效的。 But in such cases, you will not be able to call it using a base class pointer or reference, even though it points to the correct subclass object. 但是在这种情况下,即使它指向正确的子类对象,也将无法使用基类指针或引用来调用它。 You can however cast the pointer or reference to the subclass to call that method, but casting is the root of many bugs and should be avoided. 但是,您可以将指针或对子类的引用强制转换为调用该方法,但是强制转换是许多错误的根源,应避免使用。

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

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