I've got a struct "margin" in my class with 4 properties. Instead of writing four different getter/setter methods, I figured I could do it in a better way:
class myClass {
private:
struct margin {
int bottom;
int left;
int right;
int top;
}
public:
struct getMargin();
void setMargin(string which, int value);
};
But how can I set the property of the struct corresponding with the string "which" from within the function setMargin()
? For example, if I call myClass::setMargin("left", 3)
, how can I then set "margin.left" to "3"? Preferably while keeping the struct POD? I really can't figure this out...
And on a side note, is this really better than writing many getter/setter methods?
Thanks!
First, your idea is terrible... :)
Note you don't even have a margin
member (added below)
I'd use an enum
for this, if you don't want setters/getters for each property:
class myClass {
private:
struct margin {
int bottom;
int left;
int right;
int top;
} m; // <--- note member variable
public:
enum Side
{
bottom, left, rigth, top
};
struct getMargin();
void setMargin(Side which, int value);
};
and have a switch
statement inside setMargin
.
void myClass::setMargin(Side which, int value)
{
switch (which)
{
case bottom:
m.bottom = value;
break;
//....
}
}
class myClass {
private:
int margin[4];
public:
enum Side
{
bottom, left, rigth, top
};
void setMargin(Side which, int value);
};
void myClass::setMargin(Side which, int value)
{
margin[which]=value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With