Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access struct property by variable value

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!

like image 415
Frog Avatar asked Aug 13 '12 18:08

Frog


2 Answers

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;
    //....
    }
}
like image 169
Luchian Grigore Avatar answered Sep 17 '22 17:09

Luchian Grigore


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;
}
like image 29
Gir Avatar answered Sep 19 '22 17:09

Gir