Skip to content

0. C++ Introduction

:material-circle-edit-outline: 约 965 个字 :fontawesome-solid-code: 58 行代码 :material-clock-time-two-outline: 预计阅读时间 4 分钟

C++ Programming Tutorial

Introduction to C++ Programming(for Novices & First-Time Programmers)1. Getting Started - Write our First Hello-world C++ Program

1. Getting Started

英文单词记录

  1. line number 行号,即每行左边框的顺序数字记号
  2. aka 别名
  3. compilation, compile 编译
  4. preprocessor directive 预处理器指令
  5. namespace 命名空间
  6. Terminate 终止

技巧记录

  1. You should choose a filename which reflects the purpose of the program.

#include <iostream>    // Needed to perform IO operations
using namespace std;

int main() {                        // Program entry point
   cout << "hello, world" << endl;  
   return 0;                        // Terminate main()
}                                   

#include using namespace std;

The "#include" is called a preprocessor directive. Preprocessor directives begin with a # sign. They are processed before compilation.

The directive "#include <iostream>" tells the preprocessor to include the "iostream" header file to support input/output operations.

The "using namespace std;" statement declares std as the default namespace used in this program.

The names cout and endl, which is used in this program, belong to the std namespace.

These two lines shall be present in all our programs.

命名空间

工程越大,名称互相冲突性的可能性越大。
为了避免这些标识符的命名发生冲突,标准C++引入关键字 namespace,控制标识符的作用域。

//定义一个名字为A的命名空间(变量、函数)
namespace A {
    int a = 100;
}
namespace B {
    int a = 200;
}
void test02()
{
    //A::a  a是属于A中
    cout<<"A中a = "<<A::a<<endl;//100
    cout<<"B中a = "<<B::a<<endl;//200
}

cout << "hello, world" << endl;

"cout" refers to the standard output (or Console OUTput).

The symbol << is called the stream insertion operator (or put-to operator), which is used to put the string "hello, world" to the console.

"endl" denotes the END-of-Line or newline, which is put to the console to bring the cursor(游标) to the beginning of the next line.

即,endl 进行了回车换行。


return 0;

terminates the main() function and returns a value of 0 to the operating system.

Typically, return value of0 signals normal termination; whereas value of non-zero (usually 1) signals abnormal termination.

This line is optional. C++ compiler will implicitly insert a "return 0;" to the end of the main() function.

2. C++ Terminology and Syntax

英文单词记录

  1. closing brace 后大括号
  2. semicolon 分号
  3. Token 文本中的最小单位,如 字/词/符号 等等

技巧记录

  1. Use comments liberally.
  2. Use extra whitespaces and newlines liberally.

Statement vs Preprocessor Directive

A programming statement performs a piece of programming action. It must be terminated by a semicolon (;)

A preprocessor directive begins with hash sign (#). It is processed before compiling the program. A preprocessor directive is NOT terminated by a semicolon - take note of this unusual rule.

block

​ A block is a group of programming statements enclosed by braces { }.This group of statements is treated as one single unit.

Whitespaces

Blank, tab, and newline are collectively called whitespaces.

Case Sensitivity

C++ is case sensitive - a ROSE is NOT a Rose, and is NOT a rose.

3. The Process of Writing a C++ Program

CompilationProcess.png

Step 1

Write the source codes (.cpp) and header files (.h).

Step 2

Pre-process the source codes according to the preprocessor directives.

Preprocessor directives begin with a hash sign (#), e.g., #include and #define.

They indicate that certain manipulations (such as including another file or replacement of symbols) are to be performed BEFORE compilation.

Step 3

Compile the pre-processed source codes into object codes (.obj, .o).

Step 4

Link the compiled object codes with other object codes and the library object codes (.lib, .a) to produce the executable code (.exe).

Step 5

Load the executable code into computer memory.

Step 6

Run the executable code, with the input to produce the desried output.

4. C++ Program Template

英文单词记录

  1. Template 模板

5. Output via "cout <<"

英文单词记录

  1. escape sequences 转义序列
  2. system-specific 系统特定:指与特定计算机系统或操作系统相关的特性、功能或设置。
  3. flush 刷新

技巧记录

  1. 回车会进入缓冲区,用scanf输入%c时会吃入回车。可以追加getchar()来吃掉回车。
  2. if 和 else 的配对遵循就近原则。如果有if套if的情况注意通过大括号配对else。
//right
for(i=0;i<5;i++){
    if(i%2){
        for(j=0;j<10;j++)
            if(j%2)
                cout << " *";
    }else{  //HERE
        for(j=0;j<10;j++)
            if(j%2)
                cout << "* ";
    }
    cout << endl;
}  

//wron
for(i=0;i<5;i++){
    if(i%2){
        for(j=0;j<10;j++)
            if(j%2)
                cout << " *";
    else    //HERE
        for(j=0;j<10;j++)
            if(j%2)
                cout << "* ";

    cout << endl;
}  

In C++, output to the display console is done via "cout" and the stream insertion (or put-to) operator <<.

cout << "hello," << endl << "one more time. " << endl << 5 << 4 << 3 << " " << 2.2 << " " << 1.1 << endl;

A special symbol called endl (END-of-Line) can be used to produce a newline.

Whenever an endl is printed, there is no visible output, but the cursor advances to the beginning (left-margin) of the next line.

Beside the endl, you can also use '\n', you could use '\t', which denote a tab character.\n' and '\t' are known as escape sequences representing ASCII codes Hex 0A (line-feed) and Hex 09 (tab), respectively.

''\n' vs endl

Strongly recommend that use endl to print a newline, instead of '\n'. This is because line delimiter is system dependent: Windows use "\r\n"; UNIX/Linux/Mac use '\n'. The endl produces system-specific newline. Furthermore, endl guarantees that the output is flushed; while '\n' does not.

6. Input via "cin >>"

英文单词记录

  1. prompts 提示

cin >> v;

We could read more than one values in one cin statement. For example,

cin >> firstInt >> secondInt;   // Read two values into respective variables

7. What is a Program?

英文单词记录

  1. circumference 圆周,周长
  2. area 面积
  3. Dissect 解剖,剖析

A program is a sequence of instructions (called programming statements), executing one after another - usually in a sequential manner.

sequential flow

8. What is a Variable?

英文单词记录

  1. variable n. 变量
  2. prompt user for its value 提示用户输入其值
  3. notation 表示法

a variable in C/C++ has a name and a type, and can hold a value of only that particular type.

13. Mixing int and double, and Type Casting

英文单词记录

  1. Type Casting Operators 类型转换操作符
  2. explicitly 明确地

技巧记录

  1. 1/2 → 0 (take note!) and 1.0/2.0 → 0.5.

    1.0/2 → 0.5 and 1/2.0 → 0.5.

  2. You can assign an integer value to a double variable. The integer value will be converted to a double value automatically, e.g.


int is far more efficient than double, in terms of running times and memory requirement.

Some C++ compilers (e.g., g++ version 3) signal a warning for truncation, while others (e.g., g++ version 4) do not:

source.cpp:xx: warning: converting to 'int' from 'double'

type cast operator

If you are certain that you wish to carry out the type conversion, you could use the so-called type cast operator.

The type cast operation could take one of these forms in C++, which returns an equivalent value in the new-type specified.

new-type(expression);    // C++ function cast notation
(new-type)expression;    // C-language cast notation
//those are both allowed

For example,

double d = 5.5;
int i;
i = int(d);        // int(d) -> int(5.5) -> 5 (assigned to i)
i = int(3.1416);   // int(3.1416) -> 3 (assigned to i)
i = (int)3.1416;   // same as above

14. Summary

英文单词记录

技巧记录