0

我想知道这种多态性的实现在 C++ 中是否可取。

我有一个超类(cPolygon)和两个子类(cRectangle 和 cTriangle)。问题是在未包含在超类中的子类之一中实现方法是否被认为是一种好的形式,即。我应该只在 cRectangle 中创建 setSomething方法吗?如果我这样做,我是否也应该在超类 cPolygon 中创建此方法(但显然不是抽象的)?

谢谢大家皮特

#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;
}
4

1 回答 1

1

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.

于 2012-05-28T02:26:46.787 回答