【发布时间】:2017-04-29 16:22:08
【问题描述】:
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] 对象?
有没有办法调用传入对象指针的函数并在完成后返回对象指针?
【问题讨论】:
-
永远不要使用自动存储持续时间存储/泄露变量的地址,因为这些对象在其作用域存在后将不复存在。函数
void functionCall(Shape* [3])违反了这一点。 -
@UnholySheep:不,他不是。他将
arrayOfShapes声明为指向形状的指针数组。做你描述的事情是Shape (*ptr_toarray)[3];
标签: c++ pointers inheritance polymorphism