【发布时间】:2014-05-04 05:08:11
【问题描述】:
我正在开发一个绘画程序。程序将按绘制顺序存储在图形窗口上绘制的元素。我想使用“LIST”来存储绘制的形状。形状有不同的类型,即 allShapes 是父类,而 line 是子类。请告诉我如何在 allShapes 列表中存储一条线并调用它的函数。
示例代码如下:
class allShapes
{
protected:
int * points; //vertices of the shape
int color; //color of the shape
int n; //no. of points
public:
//virtual void draw()= 0;
virtual void draw()
{
}
};
class line:public allShapes
{
public:
line()
{
points = new int[4];
n = 2;
}
void draw()
{
//Code here
}
};
int main()
{
int mouse_x, mouse_y;
char key_pressed;
GP142_open(); /* Open and initialize the GP142 Graphics Window */
list<allShapes> shapes;
int quit = 0;
while (!quit) {
switch (GP142_await_event(&mouse_x, &mouse_y, &key_pressed)) {
case GP142_MOUSE:
if ((mouse_x > -490 && mouse_x<-445) && (mouse_y>305 && mouse_y < 360)) // If user selects the draw line option
{
line newLine;
shapes.push_back(newLine);
allShapes check = shapes.front();
check.draw();
}
break;
case GP142_QUIT:
quit = 1;
break;
default:
break;
}
}
}
但是程序没有调用线对象的绘制函数。我也有在 allShapes 中绘制的虚函数。如何调用 check.draw() 在屏幕上画线?
【问题讨论】:
-
你好像有切片。
-
您能否建议在上述情况下如何调用派生类函数?
-
您可以将示例范围缩小到
list<allShapes> shapes;以及从line newLine;到check.draw();的所有内容。其余的似乎是噪音。 -
如果我对
line派生自allshapes的假设是正确的,您要么需要一个指针容器或类似的容器(cough 智能指针),要么需要更改设计让客户不必担心,就像this talk。 -
我已经添加了课程代码,你现在可以解释一下吗?
标签: c++ list inheritance polymorphism