这篇博客记录了我跟着 C++ Beginner's Guide 学习 C++ 的第一天,并通过一个猜数字游戏的实践来加深对 I/O、基本数据类型、控制流等基础知识的理解。
准备开发环境
在 macOS 上,可以直接使用 clang/clang++ 来编译 C++ 代码,也可以使用 gcc/g++ 命令,因为他们 指向的均为 clang:
> gcc --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: arm64-apple-darwin22.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
> g++ --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: arm64-apple-darwin22.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
> clang --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: arm64-apple-darwin22.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
> clang++ --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: arm64-apple-darwin22.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
你也可以使用 cpp.sh
在线运行 C++ 代码。其它平台的安装方式可以参考 C++ Development Setup。
学习基础知识
首先,参考 Hello World 学习如何编写、编译并运行一个简单的 C++ 程序。
- 创建一个名为
hello.cpp
的文件,内容如下:
hello.cpp
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
- 将
hello.cpp
编译为可执行文件hello
并运行:
g++ hello.cpp -o hello && ./hello
# Hello World!
第一个简单的 hello.cpp
程序主要包含了以下几个部分:
#include <iostream>
:包含了 C++ 标准库中的iostream
头文件,该头文件包含了std::cout
和std::cin
等用于输入输出的对象。int main()
:程序的入口函数,所有的 C++ 程序都必须包含一个main
函数。std::cout << "Hello World!\n";
:输出字符串"Hello World!"
,并在末尾添加一个换行符\n
。
输入与输出
C++ 中的输入输出可以通过 std::cin
和 std::cout
对象来实现:
std::cin
:用于从标准输入(通常是键盘)读取数据。std::cout
:用于向标准输出(通常是屏幕)输出数据。
下面是一个使用 std::cin
和 std::cout
的简单示例:
io.cpp
#include <iostream>
int main() {
int a, b;
std::cout << "Enter two numbers: ";
std::cin >> a >> b;
std::cout << "The numbers you entered are: " << a << " and " << b << '\n';
}
将 io.cpp
编译为可执行文件 a.out
(未指定 -o
时的默认值)并运行:
g++ --std=c++20 io.cpp && ./a.out
# Enter two numbers: 2 3
# The numbers you entered are: 2 and 3
在上面的示例程序中:
- 输入时使用了
std::cin >> a >> b;
语句读取两个数值并分别赋值给a
和b
。 - 输出时使用了
std::cout << "The numbers you entered are: " << a << " and " << b << '\n';
语句将a
和b
的值输出到屏幕上。 >>
和<<
为流操作符,用于将数据从流中读取或写入到流中。
更多信息可以参考 Input & Output (Basics)。
变量声明与数据类型
C++ 中声明变量的语法为:
type variable = value;
例如,声明一个整型变量 a
并赋值为 5
:
int a = 5;
更多信息可以参考 Fundamental Types。