c – 继承多态函数调用

class Shape 
{
   public:
      virtual void draw() const {cout<<"draw shape"<<endl;}
};



class Point : public Shape 
{
   public:
      Point( int a= 0, int b = 0 ) {x=a; y=b;}  // default constructor
      int getx() const {return x;}
      int gety() const {return y;}
      virtual void draw() const {cout<<"draw point("<<x<<","<<y<<")\n";}
   private:
      int x, y;   // x and y coordinates of Point
};


class Circle : public Point 
{
   public:  // default constructor
      Circle( double r = 0.0, int x = 0, int y = 0 ):Point(x,y) {radius=r;}
      virtual void draw() const 
      {cout<<"draw circle("<<getx()<<","<<gety()<<","<<radius<<")\n";}
   private:
      double radius;   // radius of Circle
};

void functionCall(Shape *arrayOfShapes[3])
{
    Shape shape;
    Point point( 7, 11 );            // create a Point
    Circle circle( 3.5, 22, 8 );     // create a Circle

    arrayOfShapes[0] = &shape;
    arrayOfShapes[1] = &point;
    arrayOfShapes[2] = &circle;

}

int main()
{


    Shape *arrayOfShapes[3];

    functionCall(arrayOfShapes);
    for(int i=0; i<3; ++i)
    arrayOfShapes[i]->draw();

    return 0;
}

当我试图运行时,发生了分段错误.似乎主函数无法检索arrayOfShapes [3]对象?

有没有办法调用一个函数传入一个对象的指针,并在完成时返回对象的指针?

解决方法:

您无法在这样的本地函数中创建形状,因为将局部变量的地址放入数组会使它们在其范围之外可用:

Shape shape;
arrayOfShapes[0] = &shape; // <<== Pointer to local

但是,您可以这样做:

arrayOfShapes[0] = new Shape;
arrayOfShapes[1] = new Point( 7, 11 );
arrayOfShapes[2] = new Circle( 3.5, 22, 8 );

这种方法在动态内存中创建形状,允许在函数返回时使用它们.

注意:尽管Circle需要一个原点,但圆圈绝对不是一个点.因此,此声明在逻辑上不合理:

class Circle : public Point // This implies that Circle is a Point

虽然你可以说一个点是一个半径为零的圆,但是构造这样的继承也是一个坏主意.更好的方法是让Circle包含一个Point作为它的起源:

class Circle : public Shape 
{
   public:
      const Point origin;
      // default constructor
      Circle( double r = 0.0, int x = 0, int y = 0 ):origin(x,y),
 radius(r) {}
      virtual void draw() const 
      {cout<<"draw circle("<<origin.getx()<<","<<origin.gety()<<","<<radius<<")\n";}
   private:
      double radius;   // radius of Circle
};
上一篇:java – 使用与类关联的条目创建枚举


下一篇:如何将实现接口的类添加到ArrayList