c – 继承多态函数调用

c – 继承多态函数调用,第1张

概述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 construc
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,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 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};
总结

以上是内存溢出为你收集整理的c – 继承多态函数调用全部内容,希望文章能够帮你解决c – 继承多态函数调用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1217681.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存