c++ - 为什么在 C++ 中使用宏被认为是错误的? C++标准库的使用和使用

标签 c++ c

stackoverflow 上的大多数人都说在 C++ 中使用宏很糟糕。 我不明白这背后的想法。我知道 C++ 有替代方案 但为什么它是“错误的”?

最佳答案

让我们看看 Stroustrup 怎么说:

So, what's wrong with using macros?

Macros do not obey the C++ scope and type rules. This is often the cause of subtle and not-so-subtle problems. Consequently, C++ provides alternatives that fit better with the rest of C++, such as inline functions, templates, and namespaces.

...

And yes, I do know that there are things known as macros that doesn't suffer the problems of C/C++ preprocessor macros. However, I have no ambitions for improving C++ macros. Instead, I recommend the use of facilities from the C++ language proper, such as inline functions, templates, constructors (for initialization), destructors (for cleanup), exceptions (for exiting contexts), etc.

关于c++ - 为什么在 C++ 中使用宏被认为是错误的? C++标准库的使用和使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18568795/

相关文章:

C - 字符串链表

c - C 中的 struct typedef。变量还是类型?

c++ - 减少项目中的单例对象

c++ - 通过轻量级解析器逐行解析一个巨大的 XML 文件

c++ - 尝试使用对象指针的 boost::multi_array

c - 夏令时规则更改是否使 C 运行时库无效?

C编程: Grouping multiple strings and searching for it using an Unique key

c++ - 正在渲染随机屏幕片段 opengl - 这表明什么错误?

c++ - boost::archive::binary_oarchive = 程序崩溃?

C复数和printf