我已经查阅了关于类和构造函数的各种指南和教程,但到目前为止,如何将两者结合到我的程序中对我来说还没有意义。我觉得一些巨大的逻辑块正在逃避我。如果有人能用人类语言解释构造函数应该如何为我的函数填充变量,我将非常感激。不仅仅是如何让它做我想让它做的事情,还有为什么它对程序有意义?我今年开始学习。谢谢你。这是要在 GBA 模拟器上编译的代码,尽管我遇到的问题纯粹是从 C++ 的角度来看的。我在程序中以粗体概述了这篇文章的附加评论。到目前为止,我如何理解我正在尝试做的是:
我创建了一个构造函数,该构造函数随后在程序的主循环中获取其中函数的变量值,在该程序中我第一次初始化类对象,然后在我为我简单调用的移动重绘框的部分在应该从构造函数存储其初始值的类对象上。
#include <stdint.h>
#include <stdlib.h>
#include "gba.h"
// A class with variables.
class CHARBOX
{
public:
int init_;
int str_;
int health_;
int posx_;
int posy_;
int width_;
int height_;
int colour_; // someone advised me to name my class variables
// with a special symbol attached.
public:
// This is probably the part where I have not done things right. When this is
// compiling, there is an error saying that there is no matching function to
// call CHARBOX. Which I don`t understand completely.
// Constructor.
CHARBOX(int posx, int posy, int width, int height, int colour)
{
DrawBox(posx, posy, width, height, colour);
}
// Drawing functions.
void DrawBox(int posx_, int posy_, int width_, int height_, int colour_)
{
for (int x = posx_; x < posx_ + width_; x++)
{
for (int y = posy_; y < posy_ + height_; y++)
{
PlotPixel8(x, y, colour_);
}
}
}
};
// The entry point.
int main()
{
// Put the display into bitmap mode 4, and enable background 2.
REG_DISPCNT = MODE4 | BG2_ENABLE;
// Defining some colour palettes.
SetPaletteBG(1, RGB(90,0,0));
SetPaletteBG(2, RGB(0,90,0));
SetPaletteBG(3, RGB(0,0,90));
SetPaletteBG(4, RGB(90,90,0));
SetPaletteBG(5, RGB(90,0,90));
//Here is where the objects get initialized and the constructor is called.
// Draw the player at a starting location.
CHARBOX player(10, 24, 6, 8, 1);
// Draw the enemy at a starting location.
CHARBOX enemy(80, 24, 6, 8, 2);
// main loop.
while (true);
{
// Clear screen and paint background.
ClearScreen8(1);
// Flip buffers to smoothen the drawing.
void FlipBuffers();
// Redraw the player.
if ((REG_KEYINPUT & KEY_LEFT) == 0)
{
player.DrawBox(); // This is where the object gets called
// again to be redrawn.
posx_--;
}
if ((REG_KEYINPUT & KEY_RIGHT) == 0)
{
player.DrawBox();
posx_++;
}
if ((REG_KEYINPUT & KEY_UP) == 0)
{
player.DrawBox();
posy_--;
}
if ((REG_KEYINPUT & KEY_DOWN) == 0)
{
player.DrawBox();
posy_++;
}
WaitVSync();
}
return 0;
}