c++ 利用巨集自動生成get set 方法
阿新 • • 發佈:2018-11-04
1.非指標型別的成員變數的生成
// PropertyBuilderByName 用於生成類的成員變數
// 並生成set和get方法
// type 為變數型別
// access_permission 為變數的訪問許可權(public, priavte, protected)
#define PropertyBuilderByName(type, name, access_permission)\
access_permission:\
type m_##name;\
public:\
inline void set##name(type v) {\
m_##name = v;\
}\
inline type get##name() {\
return m_##name;\
}\
該巨集生成成員變數m_name,具體有name決定,其訪問許可權由acess_permission指定
2.指標型別的成員變數的生成
#define PointerPropertyBuilderByName(type, name, access_permission)\
access_permission:\
type* m_##name;\
public:\
inline void set##name(type* v){\
m_##name = v;\
}\
inline type* get##name(){\
return m_##name;\
}\
3.使用例項
class Test
{
PropertyBuilderByName(int, A, private)
PointerPropertyBuilderByName(double, DBV, private)
};
int main()
{
Test t;
t.setA(10);
cout << "A = " << t.getA() << endl;
double a = 12.3445;
t.setDBV(&a);
cout << "DBV: " << *(t.getDBV()) << endl;
system("pause");
return 0;
}
// PropertyBuilderByName 用於生成類的成員變數
// 並生成set和get方法
// type 為變數型別
// access_permission 為變數的訪問許可權(public, priavte, protected)
#define PropertyBuilderByName(type, name, access_permission)\
access_permission:\
type m_##name;\
public:\
inline void set##name(type v) {\
m_##name = v;\
}\
inline type get##name() {\
return m_##name;\
}\
該巨集生成成員變數m_name,具體有name決定,其訪問許可權由acess_permission指定
2.指標型別的成員變數的生成
#define PointerPropertyBuilderByName(type, name, access_permission)\
access_permission:\
type* m_##name;\
public:\
inline void set##name(type* v){\
m_##name = v;\
}\
inline type* get##name(){\
return m_##name;\
}\
3.使用例項
class Test
{
PropertyBuilderByName(int, A, private)
PointerPropertyBuilderByName(double, DBV, private)
};
int main()
{
Test t;
t.setA(10);
cout << "A = " << t.getA() << endl;
double a = 12.3445;
t.setDBV(&a);
cout << "DBV: " << *(t.getDBV()) << endl;
system("pause");
return 0;
}