问题
I have recently seen a cool c style macro play which generates automatically the setters/getters for the class. So this is what I am talking about.
#define BOOL_VARIABLE(name)\
void set##name(bool iValue)\
{\
// set the boolean
}\
const bool get##name() const\
{\
// get the boolean
}
BOOL_VARIABLE(AVariableName); // and calling them inside the class
- and now think about one of them for all string/int/double etc variables
I am aware of all avoid-macro usage type of remarks but I actually find it pretty cool because long getter/setter lines are really disturbing me. Can you think of anything that might go wrong with this approach.
回答1:
The following* is a better option (with type also as a parameter). However, I would avoid implementations to take full advantage of accessor methods, as mentioned by @justin. Your compiler will generate errors if you forget to implement them.
*http://cppkid.wordpress.com/2008/09/04/getters-and-setters-for-a-class-using-a-macro/
#define GETSET(type, var) \
private: \
type _##var; \
public: \
type Get##var() \
{\
return _##var; \
}\
void Set##var(type val) \
{\
_##var = val; \
}
回答2:
There is not a strong benefit over direct member access -- Why should it exist in the first place?
Typically, the body of the accessor is a good place for validation of inputs and state of this,
but the macro does not allow that so it really does not contribute "enough" to use (IMO) across a codebase. In typical programs, there will also often be enough variation to not justify its usage. It certainly should not be the only way to declare a variable and/or its accessors.
Just so there is no confusion: I am all for accessors and encapsulation. This macro just locks you out of their more important benefits.
来源:https://stackoverflow.com/questions/21412266/getter-setter-generation-with-multiline-stringfy-macro