c – 继承多态函数调用
发布时间:2020-12-16 10:06:14 所属栏目:百科 来源:网络整理
导读: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
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 }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读