C/C++中宏定义的使用

  • 宏在预处理阶段被替换为其定义的文本;
  • 如果宏从未被使用,则不会生成任何代码或数据,对程序无影响;
  • 宏本身不是常量或变量,仅是文本模板------其展开结果是否可修改,取决于内容;
  • 在代码中写出宏名时,会被预处理器替换为对应的文本(可能是值、代码、类型等);
  • 若需在宏中动态拼接标识符(如 C_Person),必须使用 ## 操作符,例如 C_##name
  • 宏定义不受作用域影响,但是可以通过#define定义一个宏,也可以通过#undef取消定义;
  • 宏定义不作类型检查;
  • ###只能放在#define的后面:
    • #argument表示将argument转成字符串"argument"
    • argument1##argument2表示将表示将argument1argument2拼接成一个标识符。
c++ 复制代码
#include <iostream>
#include <string>

#define DECLARE_SETTER(type, name) \
    void set_##name(const type &name) \
    { \
        m_##name = name; \
    }

#define DECLARE_GETTER(type, name) \
    type name() const \
    { \
        return m_##name; \
    }

#define DECLARE_VARIABLE(type, name) \
    type m_##name;

#define DECLARE_CLASS(className) \
class className \
{ \
public: \
    DECLARE_SETTER(std::string, name) \
    DECLARE_GETTER(std::string, name) \
\
    DECLARE_SETTER(int, age) \
    DECLARE_GETTER(int, age) \
\
private: \
    DECLARE_VARIABLE(std::string, name) \
    DECLARE_VARIABLE(int, age) \
};

#define TO_STRING(str) #str

int main()
{                                                                                                
    std::string str = TO_STRING(123);
    std::cout << str << std::endl;

    str = TO_STRING(Hello World);
    std::cout << str << std::endl;
    
    DECLARE_CLASS(Person)
    Person person;
    person.set_name("tom");
    person.set_age(23);
    
    std::cout << person.name() << " " << person.age() << std::endl;
    
    return EXIT_SUCCESS;
}
相关推荐
不想写代码的星星10 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
RuoZoe4 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛7 天前
delete又未完全delete
c++
祈安_7 天前
C语言内存函数
c语言·后端
端平入洛8 天前
auto有时不auto
c++
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php