最佳实践:函数注释应该放在C/C++代码中的哪个位置?

Pol*_*878 15 c c++

所以...我明白这可能是主观的,但我想对这方面的最佳做法有一些看法.

假设我有以下标题和.cpp文件:

标题:

// foo.h

class foo
{
public:
    int bar(int in);
};
Run Code Online (Sandbox Code Playgroud)

CPP:

// foo.cpp

int foo::bar(int in)
{
    // some algorithm here which modifies in and returns the modified value
}
Run Code Online (Sandbox Code Playgroud)

现在说我有这个功能评论:

/* 
    input:    an integer as input to algorithm foo

    output:   The result of the algorithm foo on input in

    remarks:  This function solves P = NP
*/
Run Code Online (Sandbox Code Playgroud)

最佳做法是将此函数注释放在函数声明上方的标题中还是放在cpp文件中函数定义之上?谢谢你

jco*_*der 46

我把描述评论什么头中的功能确实和评论描述如何它它cpp文件.

  • 这是合适的解决方案 - 按照惯例,头文件是有人寻找文档的第一个地方,假设没有实际的文档.我还建议使用doxygen格式,以便稍后使用自动化工具自动生成HTML /任何文档. (7认同)
  • 这个.头文件注释应该告诉你使用该函数需要知道的一切,而实现文件中的注释应该告诉你它是如何做的. (2认同)

Lir*_*una 9

我倾向于使用doxygen的格式作为头文件中的函数注释,允许窥视的程序员了解更多信息.

/**
 * Fills the handler with GIF information
 * 
 * @param filename GIF File name to be loaded
 * @return Inited GIF Handler or NULL for error
 */
pGifHandler gifHandlerLoad(const char* filename);

/**
 * Removes all data used by the GIF handler
 * 
 * @param gifHandler GIF Handler to be destroyed
 * @note This also clears palette and bitmap(s)
 */
void gifHandlerDestroy(pGifHandler gifHandler);
Run Code Online (Sandbox Code Playgroud)

想要知道某个功能如何工作的程序员应该查看.cpp文件,该文件将如何实现它的目标.


Pet*_*ete 5

我使用Doxygen,并在标头中使用简短的单行描述,并在实现文件中使用详细的多行描述。我认为这会产生更清晰的头文件,让我更容易看到。

注意: 如果您将此代码作为库发布,人们可能不想深入研究其实现。然而,头文件通常是公平的游戏。在这种情况下,我会将详细文档放在标题中。

标头:

// foo.h

class foo
{
public:
    /**\brief This function solves P = NP */
    int bar(int in);
};
Run Code Online (Sandbox Code Playgroud)

程序文件:

// foo.cpp

/** 
 \param[in]    an integer as input to algorithm foo

 \returns    The result of the algorithm foo on input in
*/
int foo::bar(int in)
{
    // some algorithm here which modifies in and returns the modified value
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*uck 5

按重要性排序:

  1. 如果它是现有项目的一部分并且存在流行的评论风格,请使用它.代码库中的一致性比单个开发人员的首选项更重要.

  2. 如果是新项目,请使用Doxygen或类似文件来记录您的代码.虽然这不能回答你的问题,因为你可以使用它们.每晚运行它,以便您拥有最新的可浏览源文档.

  3. 就个人而言,我更喜欢只在头文件中添加简短的内联函数和成员的一行摘要,否则在浏览头文件时更难以简要概述类功能.我留给.cpp文件的详细说明.一些访问者我不评论他们的目的是否真的很明显.

关于懒惰评论,我也有一个很大的烦恼,特别是单行:

例如,此评论是浪费空间,也可能被删除:

/** Get the width */
double getWidth();
Run Code Online (Sandbox Code Playgroud)

此评论很有用:

/** Get the width in inches excluding any margin. */
double getWidth();
Run Code Online (Sandbox Code Playgroud)