티스토리 뷰

IT지식

#define 으로 Set Get 만들자

민자르 2017. 1. 23. 11:27
반응형

예제

멤버 변수는 클래스안에서 선언하는 변수이므로 보통 m_ 로 시작을 한다. 예전에는 헝거리언 표기법이나 여러가지 규칙이 있긴했지만

요즘은 그렇게까지 따지면서 코딩하지는 않는 듯 하다.

 

#define SET_MEMBER( x, y, fun )          inline void Set##fun( x t ) { m_##y = t; }

#define GET_MEMBER( x, y, fun )          inline x Get##fun() { return m_##y; }

#define GET_SET_MEMBER( x, y, fun )      SET_MEMBER( x, y, fun ) GET_MEMBER( x, y, fun )


#define SETP_MEMBER( x, y, fun )         inline void Set##fun( x * t ) { m_##y = t; }

#define GETP_MEMBER( x, y, fun )         inline x * Get##fun() { return m_##y; }

#define GETP_SETP_MEMBER( x, y, fun )    SETP_MEMBER( x, y, fun ) GETP_MEMBER( x, y, fun )


class TestDefine

{

public:

TestDefine() {}

~TestDefine() {}

GET_SET_MEMBER( int, value, Value );

GETP_SETP_MEMBER( int, values, Values );

private:

int m_value;

int * m_values;

};


int main(int argc, const char * argv[])

{

TestDefine test;

test.SetValue( 10 );

int * values = new int;

values[0] = 11;

test.SetValues( values );

printf( "GET_SET_MEMBER %d\n", test.GetValue() );

printf( "GETP_SETP_MEMBER %d\n", test.GetValues()[0] );

test.SetValues( nullptr );

delete values;

        return 0;

}

실행

GET_SET_MEMBER 10

GETP_SETP_MEMBER 11

Program ended with exit code: 0


멤버변수를 private으로 지정하고 간단하게 접근이나 가져올때 사용하면 편리함



728x90
반응형
댓글