c++ - 使用 #define 指令作为代码的 "part",而不是在文件顶部

标签 c++ c-preprocessor coding-style

在查看 C++ 源代码时,我几乎总是在文件的头部看到 #define 宏,这在大多数情况下都是有意义的,我可以理解为什么这是最佳实践,但我最近遇到一种情况,将预处理器定义保留在函数体中可能会更好。

我正在写一个quaternion类,我的相关函数的代码如下所示:

Quaternion Quaternion::operator*(const Quaternion& q){
    Quaternion resultQ;

    // These are just macros to make the code easier to read,
    // 1 denotes the quaternion on the LHS of *,
    // 2 denotes the quaternion of the RHS 0f *, e.a. Q1 * Q2.
    // the letter denotes the value of the real number constant part 
    // for each seperate part of the quaterion, e.a. (a+bi+cj+dk)

    #define a1 this->get_real()
    #define a2 q.get_real()
    #define b1 this->get_i()
    #define b2 q.get_i()
    #define c1 this->get_j()
    #define c2 q.get_j()
    #define d1 this->get_k()
    #define d2 q.get_k()

    // This arithemtic is based off the Hamilton product
    // (http://en.wikipedia.org/wiki/Quaternion#Hamilton_product)
    resultQ.set_real(a1*a2 - b1*b2 - c1*c2 - d1*d2);
    resultQ.set_i(a1*b2 + b1*a2 + c1*d2 - d1*c2);
    resultQ.set_j(a1*c2 - b1*d2 + c1*a2 + d1*b2);
    resultQ.set_k(a1*d2 + b1*c2 - c1*b2 + d1*a2);
    return resultQ;
}

我决定添加#define,因为如果我手动替换所有宏,每行都会太长,并且在读取时要么被切断,要么转到下一行。我本可以对变量做同样的事情,但我认为这会是不必要的开销,所以我使用了#define,因为它没有运行时开销。这是可以接受的做法吗?有没有更好的方法让我在这里所做的事情可读?

最佳答案

而不是

#define a1 this->get_real()

auto const a1 = get_real();

只需为每个变化的数量值使用不同的名称即可。

是的,在某些情况下本地#define是有意义的。不,这不是这样的情况。特别是,由于您忘记了#undef宏,因此它们几乎肯定会导致其他代码中无意的文本替换,如果这是在 header 中(如图所示)。


顺便说一下,而不是

Quaternion Quaternion::operator*(const Quaternion& q){

我会写

Quaternion Quaternion::operator*(const Quaternion& q) const {

这样 const 四元数也可以相乘。

关于c++ - 使用 #define 指令作为代码的 "part",而不是在文件顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22738009/

相关文章:

c# - 在 C# 中使用 pragma intrinsic(sqrt, pow)?

c++ - C++ 异常处理的最佳实践是什么?

language-agnostic - 最佳实践 - 何时评估函数执行的条件

c++ - 在 C++ 函数调用中使用自增运算符是否合法?

c++ - 如何处理 C++ 重定向进程的输出

c++ - while 循环中的迭代在不接受输入的情况下运行和结束?

c - 在另一个宏声明中使用宏

c - 在宏中使用 __FUNCTION__

c++ - 如何编写连接池?

c#函数编码指南