Fro*_*rog 6 c++ struct getter-setter
我的课程中有4个属性的结构"边距".我没有写出四种不同的getter/setter方法,而是认为我可以用更好的方式做到:
class myClass {
private:
struct margin {
int bottom;
int left;
int right;
int top;
}
public:
struct getMargin();
void setMargin(string which, int value);
};
Run Code Online (Sandbox Code Playgroud)
但是如何在函数中设置与字符串"which"对应的struct的属性setMargin()?例如,如果我打电话myClass::setMargin("left", 3),我怎么能将"margin.left"设置为"3"?最好在保持结构POD的同时?我真的无法弄清楚这一点......
从旁注来看,这真的比编写许多getter/setter方法更好吗?
谢谢!
Luc*_*ore 10
首先,你的想法很糟糕...... :)
请注意,您甚至没有margin会员(在下面添加)
enum如果你不想为每个属性设置setter/getter,我会使用一个:
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);
};
Run Code Online (Sandbox Code Playgroud)
并在switch里面发表声明setMargin.
void myClass::setMargin(Side which, int value)
{
switch (which)
{
case bottom:
m.bottom = value;
break;
//....
}
}
Run Code Online (Sandbox Code Playgroud)