备注的类型:
备注在C++中是一种解释性的语言,解释程序的功能,作用等。在C++中有两种备注语言,一种是//,一种是/* */
切记第二种不能嵌套。
std::cout << "Hello world!" << std::endl; // cout and endl live in the iostream library
std::cout << "It is very nice to meet you!" << std::endl; // these comments make the code hard to read
std::cout << "Yeah!" << std::endl; // especially when lines are different lengths
/* This is a multi-line comment.
This line will be ignored.
So will this one. */
错误的备注,将/* */嵌套使用
/* This is a multi-line /* comment */ this is not inside the comment */
// The above comment ends at the first */, not the second */
合理地使用备注:
一般情况下以下备注应该用来做三件事情:
- 对于一个给出的库或者函数以及程序,备注往往用来藐视这些库,或者函数,程序的功能。如下:
这一类的备注可以让读者不用完全读完代码就知道这个代码是干什么用的,使用程序的人只要一看就可以知道程序的作用。对于现在的程序来说,都比较大。所以不能能一个人搞定所有程序,这对于现代代码的开发非常重要。// This program calculate the student's final grade based on his test and homework scores. // This function uses newton's method to approximate the root of a given equation. // The following lines generate a random item based on rarity, level, and a weight factor.
- 对于给出的库的内部函数代码来说,备注有助于买哦是代码是怎么具体实现功能的。如:
在语句层面应该备注为什么代码这么写,而不是代码执行了什么东西,这个从代码一眼就能看出来。// To generate a random item, we're going to do the following: // 1) Put all of the items of the desired rarity on a list // 2) Calculate a probability for each item based on level and weight factor // 3) Choose a random number // 4) Figure out which item that random number corresponds to // 5) Return the appropriate item
坏的备注演示:
// Set sight range to 0
sight = 0;
你能很明确的看出来该语句就是将sight设置为0,所以不需要备注。你需要知道设置成0的原因。
好的备注演示:
// The player just drank a potion of blindness and can not see anything
sight = 0;
详细介绍了sight是0的原因。
- 最后,备注应该是为了那些不知道代码干什么的读者写的。编程者经常会说“很明显该这样啊”,但是人往往很容易遗忘。以后你会感谢自己的备注的,读懂代码很容易,但是要想知道为什么这么写,需要达成什么目标非常难。
简单来说:
1.在函数,库或者程序外部的级别备注“what”
2,在函数,可或者程序内部级别备注“how”
3.在语句层面备注为什么“why“”
注释代码:
把代码去掉也就是注释代码,这里提供了一些简单的方式注释掉你的代码。
使用// 或者/* */
std::cout << 1;
std::cout << 2;
std::cout << 3;
注释掉:
// std::cout << 1;
// std::cout << 2;
// std::cout << 3;
/*
std::cout << 1;
std::cout << 2;
std::cout << 3;
*/
你往往会有以下几条里有注释掉代码:
- 你开发了一段新的代码,还没有编译成功。但是你想跑一下看有没有其他异常。这个时候你往往需要把你新写的code给注释掉,确保编译运行,在后面需要调试的时候再取消掉注释。
- 你写的代码编译有问题,但是你想先跳过去,以后再来解决编译问题。
- 调试定位问题。当你需要定位问题的时候,可以注释排除代码。
- 你需要更新就得代码成新的代码。为了防止那一天还需要旧的代码,就可以先注释掉。
在剩下的教程里,我会使用代码块中的注释来解释代码是如何工作的。聪明的读者会发现按照上面的标准来注释非常讨厌。当你读到剩下教程的注释时,你需要了解这些是具有教育意义的,而不是想要展示什么是好的注释。