Question

I've been trying to create predefined classes several times in different languages but I couldn't find out how.

This is one of the ways I tried it:

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);
}

This is in C# but I need to do the same in Java and C++ too so unless the solution is the same I would like to know how to do it in all of those.

EDIT: that code did not work, so the question was for all three languages.I got working answers for C# and Java now and I guess C++ works the same way, so thanks!

Was it helpful?

Solution 2

I think a good way in C++ is use static members :

// 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);

In your code, you access them like Color c = Color::RED;

OTHER TIPS

In Java you could use an enum to accomplish this.

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;
    }

    ... 
}

Java is very similar

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top