C++入门之基础语法学习教程

2020-01-06 15:09:53王冬梅
  • 保存文件为 hello.cpp。
  • 打开命令提示符,进入到保存文件所在的目录。
  • 键入 'g++ hello.cpp ',输入回车,编译代码。如果代码中没有错误,命令提示符会跳到下一行,并生成 a.out 可执行文件。
  • 现在,键入 ' a.out' 来运行程序。
  • 您可以看到屏幕上显示 ' Hello World '。
    
    $ g++ hello.cpp
    
    $ ./a.out
    
    
    
    Hello World
    

    请确保您的路径中已包含 g++ 编译器,并确保在包含源文件 hello.cpp 的目录中运行它。
    您也可以使用 makefile 来编译 C/C++ 程序。
    C++ 中的分号 & 块

    在 C++ 中,分号是语句结束符。也就是说,每个语句必须以分号结束。它表明一个逻辑实体的结束。
    例如,下面是三个不同的语句:

    
    x = y;
    y = y+1;
    add(x, y);
    

    块是一组使用大括号括起来的按逻辑连接的语句。例如:

    
    {
     cout << "Hello World"; // 输出 Hello World
     return 0;
    }
    

    C++ 不以行末作为结束符的标识,因此,您可以在一行上放置多个语句。例如:

    
    x = y;
    y = y+1;
    add(x, y);
    

    等同于

    
    x = y; y = y+1; add(x, y);
    

    C++ 标识符

    C++ 标识符是用来标识变量、函数、类、模块,或任何其他用户自定义项目的名称。一个标识符以字母 A-Z 或 a-z 或下划线 _ 开始,后跟零个或多个字母、下划线和数字(0-9)。
    C++ 标识符内不允许出现标点字符,比如 @、$ 和 %。C++ 是区分大小写的编程语言。因此,在 C++ 中,Manpower 和 manpower 是两个不同的标识符。
    下面列出几个有效的标识符:

    
    mohd  zara abc move_name a_123
    myname50 _temp j  a23b9  retVal
    

    C++ 关键字

    下表列出了 C++ 中的保留字。这些保留字不能作为常量名、变量名或其他标识符名称。

    asm else new this
    auto enum operator throw
    bool explicit private true
    break export protected try
    case extern public typedef
    catch false register typeid
    char float reinterpret_cast typename
    class for return union
    const friend short unsigned
    const_cast goto signed using
    continue if sizeof virtual
    default inline static void
    delete int static_cast volatile
    do long struct wchar_t
    double mutable switch while
    dynamic_cast namespace template