[Knowledge points that C++ beginners need to master]

  1. Install and configure the C++ development environment

The method of installing and configuring a C++ development environment varies depending on the operating system and IDE, and generally includes the following steps:

  • Download and install the C++ compiler
  • Download and install an integrated development environment (IDE) such as CodeBlocks, Visual Studio, etc.
  • Set compiler and IDE environment variables
  • Create and configure projects, and write, compile, and run programs

Since it involves the uniqueness of each operating system and IDE, I will not go into details here. You can perform related operations according to your own situation.

  1. Learn basic syntax and data types

The basic syntax and data types of C++ include variables, operators, control flow statements, etc. Here is some sample code:

  • Define variables and assign values
int num = 10;
float pi = 3.14;
char ch = 'a';
bool flag = true;
  • Operator examples
int a = 10, b = 5;
int c = a + b;  // 加法
int d = a - b;  // 减法
int e = a * b;  // 乘法
int f = a / b;  // 整数除法
int g = a % b;  // 取余
int h = ++a;    // 前缀自增
int i = b--;    // 后缀自减
bool j = (a == b);  // 相等比较
bool k = (a > b);   // 大小比较
  • Control flow statement example
int x = 10, y = 20;
if (x > y) {
    
           // if语句
    cout << "x is greater than y." << endl;
} else if (x < y) {
    
    
    cout << "y is greater than x." << endl;
} else {
    
    
    cout << "x and y are equal." << endl;
}

for (int i = 0; i < 5; i++) {
    
      // for循环
    cout << i << " ";
}

int i = 0;
while (i < 5) {
    
       // while循环
    cout << i << " ";
    i++;
}

do {
    
                  // do-while循环
    cout << i << " ";
    i++;
} while (i < 5);
  1. Handle input and output

The standard input and output of C++ include cin and cout, as well as file input and output. Here is some sample code:

  • Standard input and output example
int num;
cout << "Please enter a number: ";
cin >> num;
cout << "The number is: " << num << endl;
  • File input and output example
#include <fstream>
using namespace std;

int main() {
    
    
    ofstream outfile("data.txt");  // 创建写文件流对象
    if (outfile.is_open()) {
    
    
        outfile << "This is a test." << endl;  // 写入数据
        outfile.close();  // 关闭文件流
    }

    ifstream infile("data.txt");  // 创建读文件流对象
    string line;
    if (infile.is_open()) {
    
    
        while (getline(infile, line)) {
    
      // 逐行读取数据
            cout << line << endl;
        }
        infile.close();
    }
    return 0;
}
  1. Learn arrays and strings

Arrays and strings are commonly used data structures in C++ and can be initialized, assigned, traversed, etc. in various ways. Here is some sample code:

  • Array example
int arr[5] = {
    
    1, 2, 3, 4, 5};  // 定义并初始化数组
for (int i = 0; i < 5; i++) {
    
    
    cout << arr[i] << " ";     // 遍历数组
}
int arr2[] = {
    
    1, 2, 3, 4, 5};  // 定义并自动推断数组大小
string str_arr[3] = {
    
    "hello", "world", "C++"};  // 定义字符串数组
  • String example
string str1 = "hello world";   // 定义字符串
string str2("C++ programming"); // 使用构造函数定义字符串
for (int i = 0; i < str1.size(); i++) {
    
    
    cout << str1[i];           // 遍历字符串
}
string str3 = str1 + " " + str2;  // 字符串连接
  1. Familiar with function definition, calling and parameter passing

Functions are the basis of modular programming in C++ and can easily achieve code reuse and encapsulation. Here is some sample code:

  • Function definition and calling examples
int add(int a, int b) {
    
         // 定义函数
    return a + b;
}
int main() {
    
    
    int result = add(3, 4); // 调用函数
    cout << result << endl;
    return 0;
}
  • Recursive function example
int factorial(int n) {
    
          // 定义递归函数
    if (n == 1 || n == 0) {
    
    
        return 1;
    } else {
    
    
        return n * factorial(n - 1);
    }
}
int main() {
    
    
    int result = factorial(5); // 调用递归函数
    cout << result << endl;
    return 0;
}
  1. Master the basics of object-oriented programming

Object-oriented programming is an important feature of C++, supporting classes, objects, inheritance, polymorphism, etc. Here is some sample code:

  • Class and object examples
class Rectangle {
    
             // 定义类
public:
    int width;
    int height;
    int getArea() {
    
           // 定义成员函数
        return width * height;
    }
};
int main() {
    
    
    Rectangle rect;      // 创建对象
    rect.width = 10;
    rect.height = 20;
    int area = rect.getArea();  // 调用成员函数
    cout << "The area is: " << area << endl;
    return 0;
}
  • Inheritance and polymorphism example
#include <iostream>
using namespace std;

class Shape {
    
             // 定义基类
public:
    virtual void draw() {
    
      // 定义虚函数
        cout << "Drawing a shape." << endl;
    }
};

class Rectangle : public Shape {
    
       // 定义派生类
public:
    void draw() {
    
                      // 重写虚函数
        cout << "Drawing a rectangle." << endl;
    }
};

int main() {
    
    
    Shape* p;                    // 创建基类指针
    Rectangle rect;              // 创建派生类对象
    p = &rect;                   // 基类指针指向派生类对象
    p->draw();                   // 调用虚函数,实现多态
    return 0;
}
  1. Learn to use pointers

Pointers are an important data type in C++ and can be used for dynamic memory allocation, pointer operations, etc. Here is some sample code:

  • Pointer definition and usage examples
int num = 10;
int* ptr = &num;     // 定义指向int的指针,并赋值为num的地址
int val = *ptr;      // 从指针中获取值
cout << "The value is: " << val << endl;
*ptr = 20;           // 修改指针所指的值
cout << "The new value is: " << num << endl;
  • Pointer as function parameter example
void swap(int* a, int* b) {
    
      // 定义函数,使用指针作为参数
    int temp = *a;
    *a = *b;
    *b = temp;
}
int main() {
    
    
    int a = 10, b = 20;
    swap(&a, &b);            // 调用函数,传递指针参数
    cout << "a = " << a << ", b = " << b << endl;
    return 0;
}
  1. Dynamic memory allocation and deallocation

Dynamic memory allocation can dynamically allocate memory space for variables while the program is running, without the need to pre-allocate a fixed size of memory when the program is compiled. In C++, you can use the new operator to allocate dynamic memory and the delete operator to release dynamic memory. Here is a sample code:

// 动态分配一个整型变量
int *p = new int;
*p = 10;

// 动态分配一个数组
int *arr = new int[10];
for (int i = 0; i < 10; i++) {
    arr[i] = i;
}

// 释放动态分配的内存
delete p;
delete[] arr;

Note: The first piece of code dynamically allocates an integer variable p, and assigns the memory space pointed to by p to 10; the second piece of code dynamically allocates an array arr containing 10 integer elements, and assigns the elements in the array to The assignment is 0~9; the last two lines of code release the memory space pointed to by p and arr respectively.

  1. File operations

C++ provides header files related to file operations, including and. You can use the ifstream, ofstream, and fstream classes in the fstream header file to read and write files. Here is a sample code:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    // 打开一个文件进行写操作
    ofstream outfile("example.txt");
    outfile << "Hello World!" << endl;
    outfile.close();
    
    // 打开一个文件进行读操作
    ifstream infile("example.txt");
    string str;
    getline(infile, str);
    cout << str << endl;
    infile.close();
    
    return 0;
}

Note: Line 5 of code uses the ofstream class to open the file example.txt for writing, and then writes the string "Hello World!" to the file. Line 10 of the code uses the ifstream class to open the file example.txt for reading, then reads a line of content in the file and stores it in the string str for output.

  1. Common algorithms and data structures

The C++ standard library provides many commonly used algorithms and data structures, including sorting, search, stack, queue, linked list, tree, etc. You can use functions and classes in header files such as and to implement these functions. Here is a sample code:

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

int main() {
    // 排序
    int arr[] = {5, 3, 2, 4, 1};
    sort(arr, arr + 5);
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // 队列
    queue<int> q;
    q.push(1);
    q.push(2);
    q.push(3);
    while (!q.empty()) {
        cout << q.front() << " ";
        q.pop();
    }
    cout << endl;
    
    return 0;
}

Note: Line 8 of code sorts the array arr and outputs the sorted result. The 12th line of code uses the queue class to implement a queue, enqueues 1, 2, and 3 in sequence, and outputs the elements in the queue.

Guess you like

Origin blog.csdn.net/u012534326/article/details/131124288