您的位置:首页 > 编程语言 > C语言/C++

一个例子解释C++ 宏的作用

2013-02-10 21:15 162 查看
首先建立一个头文件oop.h,内容如下:

#ifndef OOP_H
#define OOP_H

#define PROPERTY_DECL(className,propertyName) \
public: className get##propertyName() { return m_##propertyName; } \
public: void set##propertyName(className val) { m_##propertyName = val; } \
private: className m_##propertyName;

#define APP_INIT(MainClass) \
int main(int argc,char **argv) \
{ \
MainClass instance;    \
}

#endif // OOP_H


PROPERTY_DECL宏的作用就是声明一个属性(类似C#的property),它具有赋值函数和取值函数,同时这个宏帮助你声明了一个private变量来存储这个值。

下面就实践一下它的使用,新建test.h:

#ifndef TEST_H
#define TEST_H

#include "oop.h"

class Test
{
PROPERTY_DECL(int,Count)   //注意这里,使用到了这个宏!
public:
Test();
};

#endif // TEST_H


test.cpp:

#include "test.h"
#include <iostream>

Test::Test()
{
setCount(10);
std::cout << "Hello!" << std::endl;
std::cout << "Function getCount() result: " << getCount() << std::endl;
}

APP_INIT(Test)


到此,编译运行一下看看效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: