将预定义的颜色添加到简单的C++颜色类

Add predefined colors to a simple C++ Color class

本文关键字:颜色 C++ 简单 添加 预定义      更新时间:2023-10-16

我需要为具有RGBA值的小型应用程序编写一个Color类。我在想有这样的东西:

class Color
{
public:
Color(int red, int green, int blue);
// stuff
private:
int m_red;
int m_green;
int m_blue;
int m_alpha;
};

我想添加使用几种预定义颜色的可能性。我见过有人使用static常量来执行此操作的示例,但我一直听说它们不是好的做法,因为它们会污染应用程序并可能导致测试问题。我想知道您认为这样做的最佳方法是什么,以及为什么。

问候

虽然我认为这个问题将主要基于意见而结束,但我会提出我的意见。

我知道避免静态常量的主要原因是,如果您内联定义它们并需要通过引用获取它们,则可能会遇到链接器错误。看到这里。由于这不是整型类型,因此您必须使类constexpr内联(在类外部)定义静态常量,或者在实现文件中在类外部定义它们。无论哪种方式都需要一个实现文件(内联 constexpr 常量版本是会导致链接器错误的版本)。

我更愿意制作这样一个简单的类 constexpr 并将预定义的颜色定义为静态 constexpr 函数:

struct Color
{
static constexpr Color red() { return Color(255, 0, 0); }
static constexpr Color green() { return Color(0, 255, 0); }
static constexpr Color blue() { return Color(0, 0, 255); }
static constexpr Color black() { return Color(0, 0, 0); }
static constexpr Color white() { return Color(255, 255, 255); }
constexpr Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255)
: r(r), g(g), b(b), a(a)
{}
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
void do_something_with_color(const Color& color)
{
printf("workedn");
}
int main()
{
do_something_with_color(Color::red());
return 0;
}

作为旁注,这是您真正处理结构的时候之一。类型的公共接口其组件,因此它们应该是公共的。这种基于函数的方法没有性能损失,避免了可能的链接器错误,并且在我看来更加灵活和干净。

使用命名空间,您可以将实例隐藏在命名空间下,但通常,它们被声明为static字段

class Color {
public:
static const int MAX = 0xffff;
Color(int red, int green, int blue, int alpha = MAX);
// stuff
static const Color red;
static const Color green;
static const Color blue;
static const Color white;
static const Color black;
// ...
private:
int m_red;
int m_green;
int m_blue;
int m_alpha;
};
const Color Color::red(MAX, 0, 0);
const Color Color::green(0, MAX, 0);
const Color Color::blue(0, 0, MAX);
const Color Color::white(MAX, MAX, MAX);
const Color Color::black(0, 0, 0);