在上一个教程中,您学习了如何编写您的第一个C++程序。现在,让我们学习 C++ 注释。
提示:我们在这本教程系列中较早介绍注释,因为从现在开始,我们将使用它们来解释我们的代码。
注释是我们添加到代码中的提示,使代码更易于阅读和理解。在 C++ 中,注释以 //
开始。
例如,
#include <iostream>
using namespace std;
int main() {
// print Hello World to the screen
cout << "Hello World";
return 0;
}
输出
Hello World
这里,// print Hello World to the screen
是一个注释。
C++ 编译器会忽略 //
符号之后的所有内容。
注意:本教程的目的是帮助您理解注释,因此您可以忽略程序中使用的其他概念。我们将在后面的教程中学习它们。
单行注释
在 C++ 中,单行注释以双斜杠(//
)符号开头。例如,
#include <iostream>
int main() {
// declaring a variable
int a;
// initializing the variable 'a' with the value 2
a = 2;
// print the value of 'a'
std::cout << "Value of a is: "<< a;
return 0;
}
输出
Value of a is: 2
在这里,我们使用了三个单行注释
// 声明一个变量
// 用值 2 初始化变量 'a'
// 打印 'a' 的值
单行注释以 //
开头,一直到行尾。我们也可以像这样在代码中使用单行注释
int a; // declaring a variable
在这里,//
之前的部分代码会被执行,而 //
之后的部分代码会被编译器忽略。
多行注释
在 C++ 中,/*
和 */
之间的任何行也都是注释。例如,
#include <iostream>
int main() {
/* declaring a variable
to store salary to employees
*/
int salary = 2000;
// print the salary
std::cout << "Salary: "<< salary;
return 0;
}
这里,/*
和 */
之间的所有内容都会被编译器忽略。此语法可用于编写单行和多行注释。
注意:记住使用注释的键盘快捷键
- 单行注释:Ctrl + / (Windows) 和 Cmd + / (Mac)
- 多行注释:Ctrl + Shift + / (Windows) 和 Cmd + Shift + / (Mac)
使用注释进行调试
注释对于调试代码非常有用。例如,
#include <iostream>
using namespace std;
int main() {
cout << "some code";
cout << ''error code;
cout << "some other code";
return 0;
}
当您的程序出现错误时,您可以使用注释暂时阻止该部分代码运行。这样您就可以在不删除代码的情况下找出问题所在。例如;
#include <iostream>
using namespace std;
int main() {
cout << "some code";
// cout << ''error code;
cout << "some other code";
return 0;
}
为什么使用注释?
我们应该出于以下原因使用注释:
- 注释使我们的代码更具可读性,便于将来参考。
- 注释用于调试目的。
- 我们可以使用注释进行代码协作,因为它可以帮助其他开发人员理解我们的代码。
注意:注释不是也不应该被用作解释写得不好的代码的替代品。总是努力编写清晰、易于理解的代码,然后将注释作为补充。
在大多数情况下,总是使用注释来解释“为什么”而不是“怎么做”,这样就足够了。
接下来,我们将学习C++ 变量、常量和字面量。