第2.1章: Hello World

English

你的第一个程序(最简版)

既然你已经知道如何编译代码,那就来写你的第一个 C++ 程序吧。 这个程序只是在屏幕上打印 Hello World。


#include <fast_io.h>

int main()
{
    using namespace ::fast_io::iomnp;
    print("Hello World\n");
}

你的第一个程序(带注释)

下面是同一个程序,但带有解释每一部分的注释:


// Single-line comment: starts with //

// Multi-line comment:
/*
   This is a multi-line comment.
   It starts with /* and ends with */.
*/

// Documentation-style comments:
/// One-line documentation comment
/**
 * Multi-line documentation comment
 */

#include <fast_io.h>  // include the fast_io library

// Every C++ program starts with a main function.
int main()
{
    // "using namespace ::fast_io::iomnp;" lets us use fast_io functions directly.
    using namespace ::fast_io::iomnp;

    // "print" writes text to the screen.
    print("Hello World\n");
}

逐项拆解

自己动手试试

把上面的最简代码保存为 main.cpp。 编译之后再运行它,你应该会看到:

Hello World

继续之前的一个警告

print 并不是一条永不会失败的魔法语句。它请求操作系统 把字节写到某处——终端、文件、管道、网络套接字 ——而这个请求可能被拒绝(磁盘满、管道已关闭、对端已 消失)。所以即使是 Hello World 也可能失败,而在 fast_io 中,每一个 可能失败的操作都以 赫布异常 的形式报告失败。

我们暂时刻意忽略这一点:接下来几页的示例会让失败 未经处理地到达 main。等我们讲到 第2.14章: A + B——第一个读取输入的程序——时, 我们就会开始妥善处理失败,而 第3.16章: 赫布异常 会讲授 完整的规则。