簡體   English   中英

靜態const顏色不能完全與Allegro5一起使用

[英]static const Color not fully working with Allegro5

我對C ++相對較新,最近從C#和Java(之前曾在純Lua環境中使用)遷移過。 我一直在嘗試解決遇到的這個問題,但是沒有成功。 基本上,我創建了一個名為Color的類,並添加了靜態const作為各種顏色的快捷方式,它用於使用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");

}
...

函數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 Color對象是在全局名稱空間中創建的。 這意味着其構造函數中的任何代碼都將在main中調用al_init之前運行。 在al_init之前只能調用幾個allegro函數,而al_map_rgb不是其中之一。

這就是為什么在al_init之后創建新的Color對象但使用靜態Color對象時不起作用的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM