类预设(如Color.Red)
Class presets (Like Color.Red)
我一直在尝试用不同的语言多次创建预定义的类,但我找不到方法。
这是我尝试的方法之一:
public class Color{
public float r;
public float r;
public float r;
public Color(float _r, float _g, float _b){
r = _r;
g = _g;
b = _b;
}
public const Color red = new Color(1,0,0);
}
这是在c#中,但我需要在Java和c++中做同样的事情,所以除非解决方案是相同的,我想知道如何在所有这些中做到这一点。
编辑:这段代码不起作用,所以这个问题是针对所有三种语言的。我现在得到了c#和Java的工作答案,我猜c++的工作方式是一样的,所以谢谢!
在Java中可以使用枚举来完成此操作。
enum Colour
{
RED(1,0,0), GREEN(0,1,0);
private int r;
private int g;
private int b;
private Colour( final int r, final int g, final int b )
{
this.r = r;
this.g = g;
this.b = b;
}
public int getR()
{
return r;
}
...
}
我认为在c++中使用静态成员是一个好方法:
// Color.hpp
class Color
{
public:
Color(float r_, float g_, float b_) : r(r_), g(g_), b(b_) {}
private: // or not...
float r;
float g;
float b;
public:
static const Color RED;
static const Color GREEN;
static const Color BLUE;
};
// Color.cpp
const Color Color::RED(1,0,0);
const Color Color::GREEN(0,1,0);
const Color Color::BLUE(0,0,1);
在您的代码中,您可以像Color c = Color::RED;
Java非常相似
public class Color {
//If you really want to access these value, add get and set methods.
private float r;
private float r;
private float r;
public Color(float _r, float _g, float _b) {
r = _r;
g = _g;
b = _b;
}
//The qualifiers here are the only actual difference. Constants are static and final.
//They can then be accessed as Color.RED
public static final Color RED = new Color(1,0,0);
}
相关文章:
- 静态自动 constexpr t = { "red" , "black" , "green" } 是什么类型;派生到?
- Red Hat:使用<atomic>编译很好,但链接器找不到__atomic_store_16;什么库?
- 给一个图 G 找到此图中的所有节点 blob,以便 node.color 属性 = 特定颜色
- 不存在从"Magick::Color"到"MagickCore::Quantum"的合适转换功能
- vim使用户定义类型的COLOR与C++中的基本类型相同
- "Color Game" - 从数组 C++ 调用随机
- 为什么"cout << Color::green"不编译?
- 是否有一种方法可以将C 代码用于Node-Red中
- 如何检查过程是否在Red Hat Linux上运行
- :void setData(const Color * & data_ptr)中的 *& 是什么意思;
- 在GCC 4.4.7 Red Hat 6.6上运行GCC 5.2
- 为什么系统("color 3")"global"?
- 为什么这段代码在Mac和Red Hat中的运行方式如此不同
- 从 S 中删除'red'组合的第一个匹配项
- 如何在Red Hat 7下使用log4cxx
- mbstowcs 在 Red Hat Linux 上返回 -1,但在 Solaris 上不返回
- DirectX Color:为什么它不能是浮点数?
- 是否有可以在控制台中设置颜色的 WinAPI 调用,如'color xx'命令?
- 性能映射 C++ 查找(G++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3))
- 类预设(如Color.Red)