C++ 中的注释
C++ 注释
程序注释是可以包含在 C++ 代码中的解释性语句。这些注释有助于任何阅读源代码的人。所有编程语言都允许某种形式的注释。
C++ 注释的类型
C++ 支持两种类型的注释:单行注释和多行注释。
下一节将详细解释 C++ 注释的类型:
1. C++ 单行注释
单行注释以 // 开头,一直到行尾。这些注释只能持续到行尾,下一行会引出新的注释。
语法
以下语法展示了如何在 C++ 中使用单行注释:
// 待注释的文本
示例
在以下示例中,我们将创建单行注释 -
#include <iostream> using namespace std; int main() { // 这是单行注释 cout << "Hello world!" << endl; // 对于新行,我们必须使用新的注释部分 cout << "This is second line."; return 0; }
输出
Hello world! 这是第二行。
2. C++ 多行注释
多行注释以 /* 开头,以 */ 结尾。这些符号之间的任何文本都仅被视为注释。
语法
以下语法展示了如何在 C++ 中使用多行注释:
/* 这是一个注释 */ /* C++ 注释也可以 跨越多行 */
示例
在下面的示例中,我们将创建多行注释 -
#include <iostream> using namespace std; int main() { /* Printing hello world!*/ cout << "Hello World!" << endl; /* This is a multi-line comment Printing another message Using cout */ cout << "Tutorials Point"; return 0; }
输出
Hello World! Tutorials Point
语句中的注释
我们也可以在 C++ 程序中注释掉代码块内的特定语句。这两种注释类型都可以实现。
示例
以下示例解释了语句中多行注释的用法 -
#include <iostream> using namespace std; int main() { cout << "This line" /*what is this*/ << " contains a comment" << endl; return 0; }
输出
This line contains a comment
示例
以下示例解释了语句中单行注释的用法 -
#include <iostream> using namespace std; int main() { cout << "This line" // what is this << " contains a comment" << endl; return 0; }
输出
This line contains a comment
嵌套注释
在 /* 和 */ 注释中,// 字符没有特殊含义。在 // 注释中,/* 和 */ 没有特殊含义。因此,您可以将一种注释"嵌套"在另一种注释中。
示例
以下示例解释了如何使用嵌套注释在注释中嵌套注释 -
#include <iostream> using namespace std; int main() { /* 注释掉 Hello World 的打印: cout << "Hello World"; // prints Hello World */ cout << "New, Hello World!"; return 0; }
输出
New, Hello World!
单行注释还是多行注释——何时使用?
单行注释通常用于简短的注释行。例如,我们需要在代码中对算法进行一些小提示。
多行注释通常用于较长的注释行,并且需要显示整行注释。注释越长,多行注释所需的语句数量就越多。
注释的用途
在 C++ 中,注释有多种用途。注释的一些主要应用领域如下:
- 简洁地表示程序中的某个步骤,以便用户更好地理解。
- 详细解释代码中未明确表达的步骤。
- 在代码中留下不同的提示,方便用户理解。
- 为了娱乐或消遣而留下注释。
- 为了调试而暂时禁用部分代码。
- 为代码添加元数据以备将来使用。
- 为代码创建文档,例如在 Github 页面中。