C++Basicstutorial

LearningC++ basicconcepts, 语法structure and DevelopmentEnvironment Setup

返回tutoriallist

1. C++Introduction

1.1 C++ history

C++ is 由Bjarne Stroustrup于1983年 in 贝尔实验室Development . 它 is Clanguage scale, 最初被称 for "C with Classes", after 来 in 1987年正式更名 for C++.

C++ design理念 is : 保持Clanguage High Efficiency and flexible性, 同时增加面向objectprogramming features, 使程序员able to更 has 效地组织 and management complex code.

1.2 C++ 特点

  • compatibility: C++兼容Clanguage, 几乎所 has C程序都可以 in C++编译器in编译run.
  • 面向object: supportencapsulation, inheritance, polymorphismetc.面向objectprogrammingfeatures.
  • 泛型programming: through模板implementation泛型programming, improvingcode reusability.
  • High Efficiency: C++程序 执行efficiency接近汇编language, 适合Development for performance要求较 high application.
  • 丰富 library: providing了标准模板library (STL) etc.丰富 libraryfunction.
  • portability: C++程序可以 in 不同 平台 on 编译run, 只需 few 量modify or 无需modify.

1.3 C++ application领域

  • system软件 and operationsystem
  • 游戏Development and graph形application
  • 嵌入式system
  • 金融领域 and high 频交易system
  • high performance计算
  • 浏览器 and Web引擎
  • datalibrarysystem
  • networkprotocolimplementation

2. DevelopmentEnvironment Setup

2.1 编译器选择

要编译 and runC++程序, 你需要一个C++编译器. 以 under is 一些常用 C++编译器:

2.1.1 GCC (GNU Compiler Collection)

GCC is 最流行 C++编译器之一, 它 is open-source , support many 种平台, includingWindows, Linux and macOS.

2.1.2 Clang

Clang is a 轻量级 C++编译器, 由LLVMprojectDevelopment, 它providing了更 good errorinformation and 更 fast 编译速度.

2.1.3 Visual C++

Visual C++ is MicrosoftDevelopment C/C++编译器, 集成 in Visual Studio IDEin, 主要用于Windows平台.

2.2 installationGCC

2.2.1 Windows平台

in Windows on installationGCC 最 simple method is usingMinGW (Minimalist GNU for Windows) or MSYS2.

  • under 载并installationMinGW
  • in installation过程in选择C++编译器
  • 将MinGW binTable of Contents添加 to systemPATHenvironmentvariablein

2.2.2 Linux平台

big many 数Linux发行版默认installation了GCC, or 者可以throughpackagemanagement器easilyinstallation:

# Ubuntu/Debian
apt-get install g++

# CentOS/RHEL
yum install gcc-c++

2.2.3 macOS平台

in macOS on , 可以throughXcodecommands行toolinstallationGCC:

xcode-select --install

2.3 集成Developmentenvironment (IDE)

除了usingcommands行编译器, 你还可以using集成Developmentenvironment (IDE) 来writing, 编译 and debugC++程序. 以 under is 一些常用 C++ IDE:

  • Visual Studio: functions强 big IDE, 主要用于Windows平台, providing了丰富 debug and analysistool.
  • Code::Blocks: open-source, 跨平台 C/C++ IDE, 轻量级且functions丰富.
  • CLion: JetBrainsDevelopment 跨平台C/C++ IDE, functions强 big 但收费.
  • Eclipse CDT: 跨平台 IDE, 需要installationC/C++Developmenttool.
  • Xcode: AppleDevelopment IDE, 主要用于macOS and iOS平台.

3. 第一个C++程序

3.1 Hello World程序

让我们writing第一个C++程序, 这 is a 经典 "Hello World"程序:

#include <iostream>

using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

3.2 程序解析

让我们analysis一 under 这个程序 各个部分:

3.2.1 #include <iostream>

这 is a 预processing指令, 用于package含C++标准输入输出library (iostream) . 这个librarypackage含了coutetc.输入输出object 定义.

3.2.2 using namespace std;

这行code表示usingstdnamespace. C++标准libraryin 所 has component都位于stdnamespacein. using这个指令 after , 我们就可以直接usingcout, endletc., 而不需要写成std::cout, std::endl.

3.2.3 int main()

这 is 主function 声明. mainfunction is C++程序 入口点, 每个C++程序都必须 has 且只 has 一个mainfunction. int表示function返回一个整数class型 值.

3.2.4 { ... }

花括号 in in 容 is function体, package含了function 具体implementation.

3.2.5 cout << "Hello, World!" << endl;

这行codeusingcoutobject输出string"Hello, World!". << is 插入运算符, 用于将 right 侧 值插入 to left 侧 输出流in. endl表示换行并刷 new 输出缓冲区.

3.2.6 return 0;

这 is function 返回语句, return value for 0, 表示程序正常结束. in mainfunctionin, 返回0通常表示程序成功执行, 非零值表示程序exception终止.

3.3 编译 and run程序

3.3.1 usingcommands行编译

fake设我们将程序保存 for hello.cpp, using以 under commands编译:

g++ hello.cpp -o hello

然 after run编译 after 程序:

# Windows
hello.exe

# Linux/macOS
./hello

3.3.2 usingIDE编译 and run

such as果你usingIDE, 通常可以through点击tool栏 on 编译 and run按钮来completion这些operation. 具体步骤因IDE而异, 但一般都非常直观.

4. C++ basic语法

4.1 标识符

标识符 is 用来命名variable, function, classetc. 名称. C++in标识符 命名规则:

  • 只能由字母, number and under 划线组成
  • 不能以number开头
  • 区分 big small 写
  • 不能usingC++ 关键字

example:

// 合法 标识符
int age;
float average_score;
char _grade;

// 非法 标识符
int 2name;     // 不能以number开头
float my-score; // 不能package含连字符
char for;       // 不能using关键字

4.2 关键字

关键字 is C++in预留 具 has 特殊含义 单词, 不能用作标识符. 以 under is C++ 一些常用关键字:

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

4.3 语句 and 分号

C++in 每个语句都以分号 (;) 结束. 分号 is 语句 终止符, 告诉编译器一个语句已经结束.

int a = 10; // 赋值语句
cout << "a = " << a << endl; // 输出语句
return 0; // 返回语句

4.4 comment

comment is 程序in不被编译器执行 文本, 用于解释code functions and 逻辑. C++support两种comment方式:

4.4.1 单行comment

// 这 is a 单行comment
int x = 5; // 这也 is a 单行comment

4.4.2 many 行comment

/* 这 is a 
    many 行comment */
int y = 10;

/*  many 行comment也可以
   用于comment掉一段code */
/*
int z = 15;
cout << "z = " << z << endl;
*/

5. dataclass型 and variable

5.1 basicdataclass型

C++providing了以 under basicdataclass型:

  • 整型: int, short, long, long long, unsigned int, unsigned short, unsigned long, unsigned long long
  • 浮点型: float, double, long double
  • 字符型: char, unsigned char, signed char
  • boolean型: bool
  • 空class型: void

5.2 variable声明 and 初始化

in C++in, variable需要先声明 after using. variable声明 语法 is :

// variable声明
int age;
double salary;
char grade;

// variable初始化
int age = 25;
double salary = 5000.50;
char grade = 'A';

// C++11及以 on versionsupport 初始化方式
int age{25};
double salary{5000.50};
char grade{'A'};

5.3 常量

常量 is in 程序run过程in值不能改变 量. in C++in, 可以usingconst关键字 or #define预processing指令来定义常量:

// usingconst关键字定义常量
const int MAX_AGE = 100;
const double PI = 3.14159;

// using#define预processing指令定义常量
#define MAX_AGE 100
#define PI 3.14159

6. 运算符

6.1 算术运算符

  • +: 加法
  • -: 减法
  • *: 乘法
  • /: 除法
  • %: 取模 (求余数)
  • ++: 自增
  • --: 自减

6.2 relationships运算符

  • ==: etc.于
  • !=: 不etc.于
  • >: big 于
  • <: small 于
  • >=: big 于etc.于
  • <=: small 于etc.于

6.3 逻辑运算符

  • &&: 逻辑 and
  • ||: 逻辑 or
  • !: 逻辑非

6.4 赋值运算符

  • =: 赋值
  • +=: 加赋值
  • -=: 减赋值
  • *=: 乘赋值
  • /=: 除赋值
  • %=: 取模赋值

6.5 运算符priority

C++in运算符 priority from high to low 排列:

  1. 括号: () [] -> .
  2. 一元运算符: ++ -- ! ~ + - * & sizeof
  3. 算术运算符: * / % + -
  4. relationships运算符: < <= > >=
  5. 相etc.运算符: == !=
  6. 位运算符: & ^ |
  7. 逻辑运算符: && ||
  8. 条件运算符: ?:
  9. 赋值运算符: = += -= *= /= %= &= ^= |= <<= >>= >>>=
  10. 逗号运算符: ,

实践case: 温度转换器

writing一个C++程序, 将华氏温度转换 for 摄氏温度.

requirementsanalysis

  • 提示user输入华氏温度
  • using公式: C = (F - 32) * 5/9 for转换
  • 输出转换 after 摄氏温度

referencecode

#include <iostream>

using namespace std;

int main() {
    double fahrenheit, celsius;
    
    // 提示user输入华氏温度
    cout << "请输入华氏温度: ";
    cin >> fahrenheit;
    
    // 转换 for 摄氏温度
    celsius = (fahrenheit - 32) * 5 / 9;
    
    // 输出结果
    cout << "华氏温度 " << fahrenheit << "°F 转换 for 摄氏温度 is  " << celsius << "°C" << endl;
    
    return 0;
}

run结果

请输入华氏温度: 98.6
华氏温度 98.6°F 转换 for 摄氏温度 is  37°C

互动练习

练习1: writing一个C++程序, 输出你 姓名 and 年龄.

提示: usingcout语句输出string and variable.

练习2: writing一个C++程序, 计算两个整数 and .

提示: usingcin语句输入两个整数, 然 after 计算它们 and 并输出.

练习3: writing一个C++程序, 将厘米转换 for 英寸.

提示: 1英寸 = 2.54厘米