非议MFC(一)宏和类型定义的困惑
关键字:C++,MFC,宏,macro,define,typedef
有感于MFC库代码之去简就繁、之故弄玄虚,作下文,聊博一笑。
请看一段常见的代码:
//in user.h
class CTest
{
private:
int x;
public:
void SetX(int setX);
int GetX() const;
operator int *();
operator const int *() const;
void * GetSafeHandle() const;
};
//in user.cpp
#include "user.h"
void CTest::SetX(int setX)
{
x=setX;
}
//...
我们(MFC的作者)认为这样的代码太浅显,不够深沉,缺少内涵,没有嚼劲。赶快include我们的头文件吧,它可以提高代码的整体形象。我们的口号是:让蓝色关键字在屏幕上消失。
//in minimfc.h
#define USER_CLASS class
#define BEGIN_CLASS_DECLARATION {
#define END_CLASS_DECLARATION };
#define PRIVATE_MEMBER private:
#define PROTECTED_MEMBER protected:
#define PUBLIC_MEMBER public:
#define OPERATOR_OVERLOAD operator
#define CONSTANT_MEMBER_FUNTION const
#define BEGIN_FUNCTION_DEFINITION {
#define END_FUNCTION_DEFINITION }
typedef void AFX_RETURN_VOID_FUNCTION;
typedef int INT;
typedef int * LPINT;
typedef const int * LPCINT;
typedef void * HOBJ;
看!我们做到了。从此,我们的客户代码将这样写:
//in user.h
#include "minimfc.h"
USER_CLASS CTest
BEGIN_CLASS_DECLARATION
PRIVATE_MEMBER
INT x;
PUBLIC_MEMBER
AFX_RETURN_VOID_FUNCTION SetX(INT setX);
INT GetX() CONSTANT_MEMBER_FUNTION;
OPERATOR_OVERLOAD LPINT();
OPERATOR_OVERLOAD LPCINT() CONSTANT_MEMBER_FUNTION;
HOBJ GetSafeHandle() CONSTANT_MEMBER_FUNTION;
END_CLASS_DECLARATION
//in user.cpp
#include "user.h"
AFX_RETURN_VOID_FUNCTION CTest::SetX(INT setX)
BEGIN_FUNCTION_DEFINITION
x=setX;
END_FUNCTION_DEFINITION
//...
本文地址:http://com.8s8s.com/it/it2053.htm