gpt4 book ai didi

c++ - 继承多态函数调用

转载 作者:太空狗 更新时间:2023-10-29 20:09:43 27 4
gpt4 key购买 nike

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

关于c++ - 继承多态函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43697921/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com