static const颜色与Allegro5不完全兼容

问题描述 投票:2回答:1

我对C ++比较陌生,最近从C#和Java转移(之前,曾经在纯Lua环境中工作)。我一直试图解决我遇到的这个问题,但没有成功。基本上,我创建了一个名为Color的类,并添加了静态consts作为各种颜色的快捷方式,它用于使用allegro进行文本编写(我正在创建自己的内部使用的游戏引擎,并在C ++中为所有库创建一个API)发动机使用)。会发生的是,当我使用静态const定义颜色时,文本不会出现,而如果我使用构造函数,则一切都按预期工作。 main_menu中的printf()函数在两种情况下都返回正确的结果,因此在任何一种情况下都会设置局部变量。所以这个问题实际上与“等式”的等位基因部分有关。

此外,如果其中任何一个格式不正确,如果有任何不良做法或类似的事情,我会很感激如何改进它的提示。

先感谢您。


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");

}
...

function 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());
}
c++ g++ allegro5
1个回答
0
投票

您的静态const Color对象是在全局命名空间中创建的。这意味着在main中调用al_init之前,其构造函数中的任何代码都会运行。 al_init之前只能调用一些allegro函数,而al_map_rgb不是其中之一。

这就是为什么它在al_init之后创建一个新的Color对象时有效,但在你使用静态Color对象时却没有。

© www.soinside.com 2019 - 2024. All rights reserved.