gpt4 book ai didi

c++ - 动画子类对象数组

转载 作者:搜寻专家 更新时间:2023-10-31 01:53:50 26 4
gpt4 key购买 nike

我正在尝试创建一个带有子类“Circle”、“Triangle”、“Rectangle”的父类“Shape”。父类保存 x 位置、y 位置和填充颜色或所有“形状”,然后每个子类保存特定于该形状的信息。有人介意查看我的代码并了解为什么我在尝试设置对象数组中的半径时收到错误“Shapes does not have a member 'setRadius'”吗...

附言现在我只有子类“Circle”,直到我开始工作。然后我将添加其他两个类。

此外,如果有人在我的代码中看到任何其他错误,我将不胜感激。

提前致谢

#include <allegro.h>
#include <cstdlib>

using namespace std;

#define scrX 640
#define scrY 400
#define WHITE makecol(255,255,255)
#define GRAY makecol(60,60,60)
#define BLUE makecol(17,30,214)

int random(int low, int high);

const int numCircles = random(1,50);

class Shape{
public:
Shape(){x = scrX / 2; y = scrY / 2; fill = WHITE;}
protected:
int x, y, fill;
};
class Circle : public Shape{
public:
Circle(){radius = 0;}
Circle(int r){radius = r;}
void setRadius(int r){radius = r;}
protected:
int radius;
};
int main()
{
// Program Initialization
allegro_init();
install_keyboard();
set_color_depth(32);
set_gfx_mode(GFX_AUTODETECT_WINDOWED, scrX, scrY, 0, 0);

// Create and clear the buffer for initial use
BITMAP *buffer = create_bitmap(scrX, scrY);
clear_to_color(buffer, GRAY);

// Set title and create label text in window
set_window_title("Bouncing Balls Ver 1.0");
textout_ex(buffer, font, "Bouncing Balls Ver 1.0", 10, 20, WHITE, GRAY);

// Draw a background box
rectfill(buffer, 50, 50, scrX-50, scrY-50, BLUE);

// Create circles
Shape **GCir;
GCir = new Shape *[numCircles];
for(int i=0;i<numCircles;i++){
GCir[i] = new Circle;
GCir[i]->setRadius(random(1,25)); // THIS IS THE ERROR
}

while(!key[KEY_ESC]){
blit(buffer, screen, 0, 0, 0, 0, scrX, scrY);
}

destroy_bitmap(buffer);

return 0;
}
END_OF_MAIN();
int random(int low, int high)
{
return rand() % (high - low) + low;
}

最佳答案

GCir[i] 的类型是 Shape* 并且 Shape 类没有 setRadius 方法,Circle 可以。因此,要么在 Circle 对象上调用 setRadius,然后再将其分配给 GCir[i],要么只构造 Circle适当的半径:GCir[i] = new Circle(random(1,25));

关于c++ - 动画子类对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10569674/

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