第 2 節

C++ Basics

0瀏覽次數0訪問次數--跳出率--平均停留

Introduction to C++

Chapter Operating Conventions

The code examples in this chapter will run in the CMake template downloaded and set up from ch1-C++开发环境与第一个工程.

Starting from this chapter, early syntax practice will only involve modifying this file.

src/main.cpp

Each example allows you to copy the code into src/main.cpp, then rebuild and run the template program.

Do not modify these files and directories for now.

  1. CMakeLists.txt
  2. src/CMakeLists.txt
  3. src/lib1/
  4. src/lib2/

No need to manually write g++ main.cpp. Let's continue using the CMake template from the previous chapter to compile the program.

Common Commands:

cmake --build --preset linux-debug
./build/linux-debug/src/cmake_template

If you haven't completed the project environment setup from the previous chapter, please start with the C++ Development Environment and First Project. This tutorial consistently uses the same CMake template. At this point, your project structure should look approximately like this.

First C++ Program

Open in the project:

src/main.cpp

It appears that your request is incomplete. Could you please provide the specific content you would like translated, or clarify what you need assistance with? I'm here to help with any translation or formatting tasks you may have.

#include <iostream>

using namespace std;

int main()
{
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。
    cout << "Hello world" << endl;

    // 返回 0 表示程序正常结束。
    return 0;
}

运行结果:

Hello world

Build and Run Program

Execute in the root directory of the project: (or you can directly use the graphical interface compilation from the previous section; I'll explain that again below)

cmake --build --preset linux-debug
./build/linux-debug/src/cmake_template

Graphical steps:

Configure to build+debug mode:

alt text

Click on the Build button in the bottom left corner.

alt text

Run

alt text

alt text

Terminal output

Hello world

The parameters of the main function

main functions do not necessarily have to take parameters. The two most common ways to write them are:

int main()
{
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。
    // 返回 0 表示程序正常结束。
    return 0;
}

运行结果: 程序正常结束,终端没有输出。

int main(int argc, char* argv[])
{
    // 程序从 main 函数开始执行,argc/argv 用来接收命令行参数。
    // 返回 0 表示程序正常结束。
    return 0;
}

运行结果: 程序正常结束,终端没有输出。

Among them:

  • argc represents the number of command-line arguments, usually at least 1, because the program's own path is also counted as an argument.
  • argv represents the command-line argument array, where argv[0] is typically the program's own path or name, and user-provided arguments start from argv[1].
  • char* argv[] can also be written as char** argv—both express the same meaning here.

Example:

#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    // 程序从 main 函数开始执行,argc/argv 用来接收命令行参数。

    cout << "argc = " << argc << endl;

    for (int i = 0; i < argc; i++) {
        cout << "argv[" << i << "] = " << argv[i] << endl;
    }

    // 返回 0 表示程序正常结束。
    return 0;
}

Run Results: See "Run Results" below; argv[0] will vary with the startup method, focus on observing the corresponding relationship between argc and each argv.

Build and run passing command-line parameters:

cmake --build --preset linux-debug
./build/linux-debug/src/cmake_template hello 123

Results

argc = 3
argv[0] = ./build/linux-debug/src/cmake_template
argv[1] = hello
argv[2] = 123

Note: argv[0] depends on the startup method—it could be ./build/linux-debug/src/cmake_template or a full path. Typically, when processing parameters, user input is read starting from argv[1].

Annotation

Purpose: Add explanations and annotations in the code to facilitate readability for yourself or other programmers.

Two Formats

  1. Single-line comment: // 描述信息
    • Typically placed above a line of code or at the end of a statement, ==as a comment describing the code==.
  2. Multi-line comments: /* 描述信息 */
    • Usually placed above a block of code, ==as a general description of that code==.

Note: The compiler ignores the contents of comments while compiling code.

variables

Function: Names a specific memory space to facilitate easier manipulation of that memory segment.

Syntax: 数据类型 变量名 = 初始值;

Example:

#include<iostream>
using namespace std;

int main() {

    //变量的定义
    //语法:数据类型  变量名 = 初始值

    int a = 10;

    cout << "a = " << a << endl;
    

    return 0;
}

运行结果:

a = 10

Note: When creating variables in C++, you must assign them an initial value; otherwise, an error will be thrown.

constant

Function: Used to record unchangeable data in a program.

There are two primary ways to define constants in C++. The first is using the const keyword, which is type-safe and commonly preferred:

const double PI = 3.14159;

The second method uses the preprocessor directive #define, inherited from C, which does not respect scope or type:

#define PI 3.14159

In modern C++, a third option, constexpr, is also available for compile-time constants:

constexpr double PI = 3.14159;

The const and constexpr methods are generally recommended for better type safety and debugging.

  1. #define macro constant: #define 常量名 常量值
    • ==Typically defined at the top of the file==, represents a constant
  2. const modified variable const 数据类型 常量名 = 常量值
    • ==Typically add the const keyword before the variable definition==, to modify the variable as a constant, unmodifiable

Example:

//1、宏常量
#define day 7

int main() {

    cout << "一周里总共有 " << day << " 天" << endl;
    //day = 8;  //报错,宏常量不可以修改

    //2、const修饰变量
    const int month = 12;
    cout << "一年里总共有 " << month << " 个月份" << endl;
    //month = 24; //报错,常量是不可以修改的
    
    

    return 0;
}

运行结果:

一周里总共有 7 天
一年里总共有 12 个月份

Keywords

Purpose: Keywords are predefined reserved words (identifiers) in C++

  • When defining variables or constants, do not use keywords.

The C++ keywords are as follows:

asmdoifreturntypedef
autodoubleinlineshorttypeid
booldynamic_castintsignedtypename
breakelselongsizeofunion
caseenummutablestaticunsigned
catchexplicitnamespacestatic_castusing
charexportnewstructvirtual
classexternoperatorswitchvoid
constfalseprivatetemplatevolatile
const_castfloatprotectedthiswchar_t
continueforpublicthrowwhile
defaultfriendregistertrue
deletegotoreinterpret_casttry

提示:在给变量或者常量起名称时候,不要用C++得关键字,否则会产生歧义。

Identifier Naming Rules

Purpose: C++ has its own set of rules for naming identifiers (variables and constants).

  • An identifier cannot be a keyword.
  • Identifiers can only consist of letters, numbers, and underscores.
  • The first character must be a letter or underscore
  • Identifiers are case-sensitive.

Suggestion: When naming identifiers, aim for intuitively clear names to facilitate reading for yourself and others.

The Relationship Between C and C++ and the Learning Path

C++ evolved from C, retaining much of C's syntax and low-level memory manipulation capabilities. C++ extends C with object-oriented programming (OOP), templates, the Standard Template Library (STL), and numerous other features, making it suitable for more complex and large-scale software development.

Suggested Learning Path:

  1. Start with C Fundamentals: Master core concepts like variables, data types, control flow (loops, conditionals), functions, arrays, pointers, and dynamic memory management.
  2. Transition to C++: Learn C++ by building on your C knowledge. Focus on key differentiators:
    • OOP Principles: Classes, objects, inheritance, polymorphism, and encapsulation.
    • Modern C++ Features: Start with auto, range-based for loops, and smart pointers, then progress to move semantics and lambda expressions.
    • STL: Become proficient with containers (vector, map, list), algorithms, and iterators.
  3. Advanced Topics & Practice: Deepen your understanding of templates, exception handling, multi-threading, and best practices. Apply your knowledge by working on projects that solve real problems.

Key Takeaway: While you can learn C++ directly, having a solid foundation in C provides a deeper understanding of how computers work at a lower level, which is invaluable for systems programming, performance-critical applications, and embedded development.

C 是一种通用的编程语言,以其简洁和高效著称,广泛用于系统软件、嵌入式系统和高性能应用开发。C++ 是在 C 的基础上发展而来,支持面向对象编程等高级特性,常用于软件开发、游戏引擎和系统软件等领域。

C and C++ are both general-purpose compiled programming languages. Besides these, common programming languages like Rust, Go, Swift, and Fortran are also compiled languages. Also Python, Rust, Go, C# (pronounced C Sharp), Java, and JavaScript; Shell is mainly used for writing command-line and system administration scripts.

C++ was initially developed from C, so the two share similarities in basic syntax, operators, flow control, Functions and pointers share many similarities. In technical documentation and toolchains that address both, In job descriptions, people often use "C/C++" as a combined term.

However, C and C++ are now two languages with independently set standards and evolved separately, so they cannot be oversimplified. for two versions of the same language:

  1. C++ is not "fully compatible with C". Most simple C code can be migrated fairly easily to C++, but there is still some valid C code that cannot be compiled directly as C++.
  2. C++ is not just "C with classes". Modern C++ also includes templates, RAII, exceptions... Lambda, smart pointers, concurrency support, and a rich standard library.
  3. C is not an outdated language replaced by C++. Operating systems, embedded development, drivers, ... C is still widely used in low-level libraries and cross-language interfaces.

Therefore, C and C++ share a common foundation but have their own suitable programming approaches. Learning one of these It certainly helps in understanding another language, but when writing C++, one shouldn't just blindly replicate C-style code.

FeaturesC languageC++ language
Language localizationCompact and focused, emphasizing direct low-level operations.More features, supporting abstraction from low-level to high-level.
Programming paradigmPrimarily employs procedural programming.Multi-paradigm: procedural, object-oriented, generic, functional, etc.
Resource managementManual handling of resource allocation and releaseManual management is supported, but RAII and smart pointers are recommended.
Abstraction and ReuseFunctions, Structures, Macros, and Modular Filesfunctions, classes, templates, generic algorithms, and standard libraries
Standard libraryC standard libraryThe C++ standard library also provides support for most C standard library functions.
type systemRelatively simple, some implicit conversions are lenient.The type system is more feature-rich and typically offers stricter checks.
Operational efficiencySuitable for high-performance and low-level development.Equally suitable for high-performance development, reasonable abstraction typically incurs no additional overhead.
Common scenariosEmbedded systems, operating systems, drivers, low-level librariesgames, graphics, robots, desktop software, infrastructure, and high-performance computing

Application scenarios in the table are not rigid boundaries. For example, embedded systems can also use C++, and large Applications may also contain C modules. Ultimately, the choice of language depends on project requirements, runtime environment, existing ecosystem and team experience.

Should you learn C first or jump straight into C++?

Learning C++ doesn't require you to fully complete C first. For readers of this tutorial, it's recommended to follow the C++ approach directly as suggested. Route Learning:

  1. First, master variables, branching, loops, functions, arrays, and basic input/output.
  2. Then continue learning about references, pointers, structs, classes, and objects.
  3. Continue learning std::string, std::vector, iterators, and common algorithms.
  4. Then understand RAII, smart pointers, templates, Lambda, and exception handling.
  5. Finally, complete a real-world project using CMake, debuggers, unit tests, and third-party libraries.

If later there is a need for embedded, operating system, driver, or pure C project development, then systematically supplement C. Arrays and pointers in the language, memory layout, structs, preprocessors, and manual resource management will be more... pertinence

This tutorial primarily focuses on C++. When encountering syntax common to the C language, we will briefly explain it, but the examples will Adopt modern C++ practices instead of treating C++ as merely an extension of C.

Supplementary Learning Resources

This tutorial is mainly designed to organize knowledge points, the engineering environment, and common issues that are frequently encountered during practice. Beginners also I18N_PROTECTED_0 Can be learned in combination with the following videos or documents.

  1. C++ Video Tutorial
  2. Peng Ge C programming video
  3. TutorialsPoint: C Tutorial
  4. Tutorials: C++ Tutorial

Different references may use varying C++ standards and coding styles. When learning syntax, you can refer to multiple. Sources may vary, but within this tutorial project, follow the C++ coding style and CMake configuration presented in the current chapter.

音乐页