2.1 Hello World 代码
x/* helloworld.cpp */using namespace std;
int main() { cout << "hello world c++!" << endl; return 0;}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/Linux | clang++ helloworld.cpp -o helloworld |
| Dev-C++ | Windows | 图形界面 IDE |
| Visual Studio | Windows | 图形界面 IDE |
编译命令:
xxxxxxxxxxg++ -std=c++11 helloworld.cpp -o helloworld./helloworld提示:建议使用
-std=c++11或更高标准,以启用现代 C++ 特性。
设置 C++ 标准(Dev-C++):
Tools → Compiler → Settings → Code Generation → Language standard → ISO 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字