静态const颜色无法与Allegro5完全合作

static const Color not fully working with Allegro5

本文关键字:Allegro5 const 颜色 静态      更新时间:2023-10-16

我对C 的新人相对较新,最近从C#和Java移动(在此之前,曾经在纯LUA环境中工作)。我一直在尝试解决我遇到的这个问题,但没有成功。基本上,我创建了一个名为Color的类,并添加了静态常量作为各种颜色的快捷方式,它用于使用Allegro进行文本编写(我正在创建自己的游戏引擎以供内部使用,并且正在为所有库中的C 创建一个API发动机用途)。发生的事情是,当我使用静态常量定义颜色时,文本不会出现,而如果我使用构造函数,则一切都按预期工作。Main_Menu中的printf()函数在两种情况下都返回适当的结果,因此在任何一种情况下都设置了本地变量。因此,问题确实在于"方程式"的Allegro部分。

另外,如果其中任何一种是畸形的,例如有任何不良的做法或类似的方法,我将感谢有关如何改进它的提示。

预先感谢您。


color.hpp

#pragma once
#include "allegro5/color.h"
#include "onidrive/vector2.hpp"
namespace oni {
  enum Align: int;
  class Font;
  class Color {
    public:
      Color(unsigned char r = 0xFF, unsigned char g = 0xFF, unsigned char b = 0xFF, unsigned char a = 0xFF);
      ~Color();
      unsigned char r;
      unsigned char g;
      unsigned char b;
      unsigned char a;
      static const Color white;
      static const Color black;
      static const Color red;
      static const Color green;
      static const Color blue;
      static const Color yellow;
      static const Color magenta;
      static const Color cyan;
      friend void draw_text(Font *font, Color *color, Vector2<float> position, Align align, std::string text);
    private:
      ALLEGRO_COLOR color;
  };
}

color.cpp

#include "onidrive/color.hpp"
#include "allegro5/allegro.h"
oni::Color::Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a) : r(r), g(g), b(b), a(a) {
  this->color = al_map_rgba(r, g, b, a);
}
oni::Color::~Color() {
}
const oni::Color oni::Color::white(  0xFF, 0xFF, 0xFF, 0xFF);
const oni::Color oni::Color::black(  0x00, 0x00, 0x00);
const oni::Color oni::Color::red(    0xFF, 0x00, 0x00);
const oni::Color oni::Color::green(  0x00, 0xFF, 0x00);
const oni::Color oni::Color::blue(   0x00, 0x00, 0xFF);
const oni::Color oni::Color::yellow( 0xFF, 0xFF, 0x00);
const oni::Color oni::Color::magenta(0xFF, 0x00, 0xFF);
const oni::Color oni::Color::cyan(   0x00, 0xFF, 0xFF);

main_menu.cpp

...
void MainMenu::draw_ui() {
  //when this is used, compiling, text is invisible
  oni::Color color = oni::Color::red;
  //when this is used, compiling, text is visible, correct color, works as expected
  oni::Color color = oni::Color(0xFF, 0x00, 0x00, 0xFF);
  printf("color(%X, %X, %X, %X);n", color.r, color.g, color.b, color.a);
  oni::draw_text(font, &color, Vector2<float>(32, 32), oni::ALIGN_LEFT, "Hello World");
}
...

功能draw_text

void oni::draw_text(Font *font, Color *color, Vector2<float> position, oni::Align align, std::string text) {
  al_draw_text(font->font, color->color, position.x, position.y, (int)align, text.c_str());
}

您的静态const颜色对象是在全局名称空间中创建的。这意味着其构造函数中的任何代码在主机中都调用之前运行。在Al_Init之前只能调用几个Allegro功能,而Al_Map_RGB不是其中之一。

这就是为什么当您在al_init之后创建一个新的颜色对象时起作用,而在使用静态颜色对象时则不行。