第一个 C++ 程序
第一个 C++ 程序

第一个 C++ 程序

2.1 Hello World 代码

2.2 代码详解

代码说明
#include <iostream>引入输入输出流库(注意:C++ 不使用 .h 后缀)
using namespace std;使用标准命名空间
int main()主函数,程序入口
cout <<输出到标准输出(类似 C 的 printf)
endl换行并刷新缓冲区(等同于 \n + flush)
return 0;返回 0 表示程序正常结束

2.3 编译与运行

编译器选择:

编译器平台命令
g++Linux/macOS/Windows (MinGW)g++ helloworld.cpp -o helloworld
clang++macOS/Linuxclang++ helloworld.cpp -o helloworld
Dev-C++Windows图形界面 IDE
Visual StudioWindows图形界面 IDE

编译命令:

提示:建议使用 -std=c++11 或更高标准,以启用现代 C++ 特性。

设置 C++ 标准(Dev-C++):

ToolsCompilerSettingsCode GenerationLanguage standardISO C++11

2.4 C 与 C++ 输出对比

C 语言C++说明
#include <stdio.h>#include <iostream>头文件不同
printf("hello\n");cout << "hello" << endl;输出语法不同
scanf("%d", &a);cin >> a;输入语法不同
需要格式符 %d%f自动类型推断C++ 更智能

23,816字