基本组成:
一般来说 一个标准的C++ 程序通常由处理命令,函数,语句,变量,输入,输出及注释等几个部分组成
- 预处理命令:在C++程序中,预处理命令以 # 开始。 C++提供三种预处理命令: 宏定义命令,文件包含命令以及条件编译命令
- 函数:一个C++程序通常由若干个函数组成,,但必须有且仅有一个主函数main,不论主函数位于什么位置,该程序都是从主函数开始执行
- 语句:是组成程序的基本单元
- 变量:在C++程序中,需要将数据放于内存单元中,而变量就是用来存储和访问内存单元中数据的标识符
- 输入/输出:在C++ 程序中,经常要使用到输入输出语句,用于接收用户的输入及程序的运行结果
- 注释:注释可以帮助读者阅读源程序,但不参与程序 运行
std::cout << "Hello World" << std::endl;
cout 的后面依次为插入运算符<<(帮助数据插入输出流)要插入的字符串字面量Hello World ,使用std::endl 表示换行符
std::cin >> Variable;
cin 后面依次为提取运算符>>(从输入流中提取数据)以及要将数据存储到其中的变量。
使用cout 和std 名称空间中的其他功能时, 在代码中添加std 限定符很繁琐。为了避免添加该限定符,可使用声明 using namespace
// Preprocessor directive
#include <iostream>
// Start of your program
int main() {
// Tell the compiler what namespace to search in
**using namespace std;**
/* Write to the screen using std::cout */
cout << "Hello World" << endl;
// Return a value to the OS
return 0;
}
另一种用法:
// Preprocessor directive
#include <iostream>
// Start of your program
int main() {
**using std::cout;**
**using std::endl;**
/* Write to the screen using std::cout */
cout << "Hello World" << endl;
// Return a value to the OS
return 0;
}
问:#include 的作用是什么?
答:这是一个预处理器编译指令。预处理器在您调用编译器时运行。该指令使得预处理器将 include 后面的<>中的文件读入程序,其效果如同将这个文件输入到源代码中的这个位置。
问:什么情况下需要命令行参数?
答:需要提供让用户能够修改程序行为的选项时。例如,Linux 命令 ls 和 Windows 命令 dir 都显示 当前目录(文件夹)的内容,要查看另一个目录中的文件,需要使用命令行参数指定相应的路径,如 ls /或 dir \。