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;
}
相关推荐
m0_736919101 分钟前
编译器命令选项优化
开发语言·c++·算法
Jiu-yuan3 分钟前
C++函数
c++
Stream_Silver3 分钟前
【Agent学习笔记1:Python调用Function Calling,阿里云API函数调用与DeepSeek API对比分析】
开发语言·python·阿里云
froginwe114 分钟前
CSS3 多媒体查询实例
开发语言
naruto_lnq9 分钟前
C++中的工厂方法模式
开发语言·c++·算法
独自破碎E9 分钟前
LCR_019_验证回文串II
java·开发语言
一切尽在,你来10 分钟前
C++多线程教程-1.2.3 C++并发编程的平台无关性
开发语言·c++
坚持就完事了13 分钟前
Java中的一些关键字
java·开发语言
雨季66622 分钟前
Flutter 三端应用实战:OpenHarmony “专注时光盒”——在碎片洪流中守护心流的数字容器
开发语言·前端·安全·flutter·交互
新缸中之脑29 分钟前
Moltbook 帖子精选
开发语言·php