将预定义的颜色添加到简单的C++颜色类
Add predefined colors to a simple C++ Color class
我需要为具有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);
相关文章:
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 如何在内核C++中使用1920x1080x16M图形或类似的16M颜色?(VGA)
- 如何在24位SDL_Surface上设置像素的颜色
- 如何从SDL_Surface获取特定像素的颜色
- 列表视图更改选择颜色
- GtkTreeView 交替行颜色
- dx11 渲染到纹理仅显示透明颜色
- 使用 OpenGL 4.5 更改所选顶点的颜色
- 为什么我的 LEGACY OPENGL 颜色反转了?
- 双击更改 mfc 中列表控件中的行的颜色
- 更改 QT 中按钮的颜色
- 当我使用CHAR_INFO结构时,控制台会无缘无故地改变颜色
- 列表视图项的替代颜色
- GLSL 将 uint 转换为浮点颜色
- std::带有颜色和标题的 clog 包装器无法正确打印整数
- Vec3b:r/g/b 颜色的最大值为 254,而不是 255
- 如何将矢量对象更改为不同的颜色?
- PPM 颜色显示错误
- 如何更改 QGraphicsItem 对象的颜色?
- 如何防止每次 Arduino 启动时颜色数组都是相同的随机数组