Say for example that we want to design a color class, assuming that we only allow for 3 different color values: Red, Green, Blue.
How is this generally achieved in C++? Or better what is the general design pattern for this?
The only way I could think of, is to initialize 3 different static colors in the Color class,, make the colourCode inaccessible and allow construction of a new Color only with an already existing one.
class Colour
{
public:
static const Colour Red;
static const Colour Green;
static const Colour Blue;
Colour(){}
bool operator==(const Colour &other) const{
if(other.colourCode == this->colourCode){return true;}else{return false;}
}
Colour & operator=(const Colour & other){
this->colourCode = other.colourCode;
}
Colour(const Colour & other){
*this = other;}
private:
int colourCode;
Colour(int colourCodeIn){
colourCode = colourCodeIn;
}
};
const Colour Colour::Red(1);
const Colour Colour::Green(2);
const Colour Colour::Blue(3);
class Pen
{
public:
Pen(){}
void setColour(const Colour & infarbe){
farbe = infarbe;
}
Colour farbe;
};
int main()
{
Pen myPen1;
myPen1.setColour(Colour::Blue);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire