5

如果将指针传递给只读函数,则该指针是 IN 参数。

如果一个指针被传递给一个只读函数,但是这个函数复制了一个指针以便在模块相关函数中访问它以进行只读操作,这个指针仍然是 IN。

如果函数仍然使用指针作为只读,但其他与模块相关的函数使用指针进行写操作,那么指针是什么?一个 IN 参数,但没有 const?输入/输出参数?

我的意思的例子:

class SteeringWheel {
        public: float rotation;
        public: SteeringWheel(void) {
                this->rotation = 0.f;
        }
};

class Car {
        private: SteeringWheel *steeringWheel;
        public:

        /**
         * @param[?] steeringWheel Is the steering wheel in or in/out? 
         */
        Car (SteeringWheel *steeringWheel) {
                this->steeringWheel = steeringWheel;
        }

        /**
         * @param[in] degree Steering amount in degrees.
         */
        void steer(float degree) 
        {
                this->steeringWheel->rotation += degree;
        }
};

int main(int argc, char **argv)
{
        SteeringWheel steeringWheel();

        /* car() uses steeringWheel as read only. */
        Car car(&steeringWheel);

        /* steer() uses steeringWheel from car() to write. */
        car.steer(50.f);

        return 0;
}
4

2 回答 2

16

我相信inandout说明符并不完全符合您的想法。从标签的doxygen 文档中param

\param 命令有一个可选属性,(dir),指定参数的方向。可能的值是“[in]”、“[in,out]”和“[out]”,请注意本描述中的 [方] 括号。当一个参数既是输入又是输出时,[in,out] 被用作属性。

参数的方向通常有以下含义:

  • in: 参数作为输入注入到函数中,但不写入。
  • out: 参数被注入到函数中,但不作为输入。相反,它是由函数写入的。
  • in, out: 参数作为输入注入到函数中,最终由函数写入。

在您的示例中:

/**
* @param[?] steeringWheel Is the steering wheel in or in/out? 
*/
Car (SteeringWheel *steeringWheel) {
    this->steeringWheel = steeringWheel;
}

我认为该steeringWheel参数是in因为您将其注入并在您的方法中使用它。但是,您永远不会写入它(即参数本身),所以它不是out. 换句话说,您只使用您的方法将地址注入您的函数,没有别的。这同样适用于您的第二种方法,您在其中注入degree参数,但从不写入它。

为了更清楚地说明 and 的含义inout下面是一个out参数示例:

/**
 * @param[out] p_param We write to the parameter!
 */
void makeFour(int * p_param)
{
    *p_param = 4; // Out because of this line!
}

请注意,我们将新值直接写入参数。这就是out的意思:信息通过参数从方法中出来。你现在可以写:

int main()
{
    int myInt = 0;
    std::cout << myInt;    // prints 0.

    makeFour(&myInt); // p_param == &myInt here.
    std::cout << myInt;    // prints 4: the method wrote directly 
                           // in the parameter (out)!

    return 0;
}

希望这可以帮助!

于 2017-12-17T14:43:25.597 回答
3

这并不容易决定,但我仍然会将您的参数标记为in,out(或out),因为它是指向非常量对象的指针,您可以稍后直接或间接更改该外部对象的状态 - 如您的示例.

标记它in隐藏了指向SteeringWheel对象稍后可能会在使用Car.

此外,它可能会让用户感到困惑,为什么不标记仅输入的指针参数const

制作它in,out可能不完全准确,但肯定更容易出错。

替代方案可能类似于以下内容(无论如何,关于 SteeringWheel 的生命周期的注释应该在这里派上用场):

    /**
     * @param[in] steeringWheel Pointer to the SteeringWheel object.
     * @warning The memory address of the pointed object is saved.
     * It must outlive this object, and can change upon usage of this object.
     */
    Car (SteeringWheel *steeringWheel) {
            this->steeringWheel = steeringWheel;
    }

但我可能会坚持标记它in,out

在 C++ 中指定参数的方向可能很复杂,坦率地说,我不太赞成它们,因为指针、引用的标记和 constness 的关键字在签名中提供了关于参数如何可能的足够信息用过的。因此,在 DoxyPress 文档中对其进行标记有点多余,不够表达(如您的示例所示),并且可能与实现不同步。如果其他语言在函数签名中缺少这些附加结构,则记录参数方向可能会发挥更大的作用。

于 2021-01-06T18:30:59.443 回答