我一直在尝试用不同的语言多次创建预定义的类,但我找不到如何。
这是我尝试过的方法之一:
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 ++的工作方式是一样的,谢谢!答案 0 :(得分:3)
在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;
}
...
}
答案 1 :(得分:1)
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);
}
答案 2 :(得分:1)
我认为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;