c++快速入门【一小时速通版】(适合预习了解、复习备忘)

C++系列文章目录

第一篇 C++快速入门【环境配置 】
第二篇 C++快速入门【一小时速通版】(√ 本文)


提示:本节以下是C++基础速通版,详细教程请参阅上述目录

文章目录


前言

目的:速通一遍C++,熟悉基本用法,不求深入
说明:学习自用,根据以下视频整理,大家可以参考学习。

参考资料:

  1. 【B站 这可能是史上最快学习C++的课程,期末考前复习冲刺的宝典】
    https://www.bilibili.com/video/BV15Y411j7JW/?spm_id_from=333.999.0.0&vd_source=15355d30d39fe89acd7ef49fef8eabb0

  2. 【w3cschool C++教程】
    https://www.w3cschool.cn/cpp/cpp-intro.html


提示:以下是本篇文章正文内容,下面案例可供参考

0. C环境+VSCode配置

参考我的上一份教程

1. 基础知识

1.1 hello world (语法)

第一个简单的Hello world程序

#include <iostream>     //包含头文件iostream,包含输入输出流
using namespace std;    //使用标准命名空间std,包含cout、cin、endl等

int main(){             //主函数,程序从此处开始执行
    cout << "Hello World!" << endl; //输出Hello World!
    return 0;        //返回0,表示程序正常结束
}

输出结果:
在这里插入图片描述

1.2 Hello world plus(std::语法)

观察程序1.2 和 1.1:

  • using namespace std是一种命名空间的使用方式,它的作用是用于在当前作用域内引入命名空间std中的所有名称。这样一来,在程序中就可以直接使用std命名空间中的名称,而无需再写std::前缀。

  • std::是命名空间的限定符,它的作用是指定名字的空间范围。例如,std::cout,表示cout是在std命名空间下面的,也就是在std命名空间中的全局作用域下声明的。

区别:

  • using namespace std是一种简化写法,它将std命名空间中的名称全部导入到当前作用域中,这可能会导致命名冲突问题。而使用std::则可以明确指定名称所在的命名空间,可以避免命名冲突。
  • using namespace std只适用于当前作用域,而std::可以用于任何作用域,包括全局作用域,也就是说,使用std::可以避免一些不必要的重新定义。
  • using namespace std可能会影响程序的可读性和可维护性,建议在头文件中使用std::来明确指定命名空间。
  • 使用using namespace std有时会导致名称冲突,特别是在大型程序中,因此不建议滥用。
#include <iostream>

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

2.1 output (输出)

一些输出示例展示
vscode注释或取消注释:ctrl+/

#include <iostream>
using namespace std;

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

// int main(){
//     cout << "Hello World!";
//     cout << "I am learning C++";
//     return 0;
// }

int main(){
    cout << "Hello World!" << "I am learning C++";
    return 0;
}

2.2 output plus (\n输出)

#include <iostream>
using namespace std;


// int main(){
//     cout << "Hello World!\n";  // \n回车,输出结果换行
//     cout << "I am learning C++";
//     return 0;
// }

// int main(){
//     cout << "Hello World!\n\n";  // \n回车,输出结果换行
//     cout << "I am learning C++";
//     return 0;
// }

int main(){
    cout << "Hello World!" << endl;  // endl回车,输出结果换行 
    cout << "I am learning C++";
    return 0;
}

3.1 comments(注释)

#include <iostream>
using namespace std;

int main(){
    cout << "Hello World!" << endl;  // 这是单行注释
    cout << "I am learning C++";    
    /*这是
多行注释*/
    return 0;
}

4.1 variables(变量)

# include<iostream>
using namespace std;

int main(){
    int myNum = 15;
    cout << myNum << endl;
///
    int myNum1;     // 声明变量
    myNum1 = 15;    // 赋值
    cout << myNum1 << endl;
///
    int myNum2 = 15;
    myNum2 = 10;
    cout << myNum2 << endl;
///
    int myNum3 = 15;            //整型Integer
    double myFloatNum = 5.99;   //浮点型Float
    char myLetter = 'D';        //字符型Character
    string myText = "Hello";    //字符串String
    bool myBoolean = true;      //布尔型Boolean
///
    int myAge = 35;
    cout << "I am " << myAge << " years old." << endl;
///
    int x = 5;
    int y = 6;
    int z = 50;
    int sum = x + y + z;
    cout << sum << endl;
///
    int x1 = 5, y1 = 6, z1 = 50;
    cout << x + y + z   << endl;
    return 0;
}

输出:

15
15
10
I am 35 years old.
61
61

4.2 variables(变量 const常量、变量命名规则)

#include <iostream>
using namespace std;

int main(){
    const int minutesPerHour = 60;  // 常量,一小时60分钟
    const float PI = 3.14159;       // 常量,圆周率

    const int myNum=15;             // 常量,整数
    myNum = 10;                     // 错误,常量不能被修改
    return 0;
}

在这里插入图片描述

5.1 input(输入)

#include<iostream>
using namespace std;

int main(){
    int x;
    cout << "请输入一个整数:";
    cin >> x;
    cout << "你输入的整数是:" << x << endl;
    return 0;
}

5.2 input(输入)

#include<iostream>
using namespace std;

int main(){
    int x,y;
    int sum;
    cout << "请输入一个整数:";
    cin >> x;
    cout << "请输入另一个整数:";
    cin >> y;
    sum = x + y;
    cout << "两个整数的和是:" << sum << endl;
    return 0;
}

6.1 DataTypes(数据类型、ASCII码)

C++基本数据类型

代码示例

#include<iostream>
using namespace std;

int main(){
    cout << "type\t" << "value\t" << "size" << endl; // \t是制表符,用于对齐

    int myNum = 5; // Integer (whole number without decimals)
    cout <<  "int\t" << myNum << '\t' << sizeof(myNum) << endl; // sizeof()是C++的内置函数,用于计算变量的字节数

    float myFloatNum = 5.99; // Floating point number (with decimals)
    cout << "float\t" << myFloatNum << '\t' << sizeof(myFloatNum) << endl;

    double myDoubleNum = 9.98; // Floating point number (with decimals)
    cout << "double\t" << myDoubleNum << '\t' << sizeof(myDoubleNum)<< endl;

    float f1 = 35e3; // Scientific numbers
    double d1 = 12E4;
    cout << "float\t" << f1 << '\t' << sizeof(f1) << endl;
    cout << "double\t" << d1 << '\t' << sizeof(d1) << endl;

    char myLetter = 'D'; // Character 
    cout << "char\t" << myLetter << '\t' << sizeof(myLetter) << endl;

    bool myBoolean = true; // Boolean
    cout << "bool\t" << myBoolean << '\t' << sizeof(myBoolean) << endl;

    string myText = "Hello"; // String
    cout << "string\t" << myText << '\t' << sizeof(myText) << endl;

    return 0;
}

输出:

type    value   size
int     5       4
float   5.99    4
double  9.98    8
float   35000   4
double  120000  8
char    D       1
bool    1       1
string  Hello   32

ASCII表

在这里插入图片描述

6.2 DataTypes(数据类型)

#include <iostream>
using namespace std;

int main(){
    string greeting = "Hello";
    cout << greeting << endl;
    return 0;
}

7.1 Operators(运算 加减乘除取余+±-)

#include <iostream>
using namespace std;

int main(){
    int x = 5;
    int y = 3;

    cout << x + y << endl; // 8
    cout << x - y << endl; // 2
    cout << x * y << endl; // 15
    cout << x / y << endl; // 1
    cout << x % y << endl; // 2
    cout << x++ << endl; // 5 先执行cout,再执行x = x + 1
    cout << x-- << endl; // 6 
    cout << ++x << endl; // 6 先执行x = x + 1,再执行cout
    cout << --x << endl; // 5
    cout << y++ << endl; // 3
    cout << y-- << endl; // 4
    cout << ++y << endl; // 4
    cout << --y << endl; // 3
    return 0;
}

7.2 Operators(运算)

#include <iostream>
using namespace std;

int main(){
    int x = 5;
    x +=3;
    cout << "x += 3: " << x << endl; // 8

    x = 5;
    x -=3;
    cout << "x -= 3: " << x << endl; // 2

    x = 5;
    x *=3;
    cout << "x *= 3: " << x << endl; // 15

    x = 5;
    x /=3;
    cout << "x /= 3: " << x << endl; // 1

    return 0;
}

7.3 Operators(运算)

#include <iostream>
using namespace std;

int main(){
    int x = 5;
    int y = 3;

    cout  << (x == y) << endl; // 0 返回的是布尔型
    cout  << (x != y) << endl; // 1
    cout  << (x > y) << endl; // 1
    cout  << (x < y) << endl; // 0
    cout  << (x >= y) << endl; // 1
    cout  << (x <= y) << endl; // 0

    return 0;
}

7.4 Operators(运算 与或非 )

#include <iostream>
using namespace std;

int main(){
    cout << (true && false) << endl; // 0
    cout << (true || false) << endl; // 1
    cout << (!true) << endl; // 0

    return 0;
}

8.1 String(字符串)

代码示例

#include <iostream>
using namespace std;

int main(){
    string firstName = "John ";
    string lastName = "Doe";
    string fullName = firstName + lastName;
    cout << fullName << endl;

    fullName = firstName + " " + lastName;
    cout << fullName << endl;

    fullName = firstName.append(lastName);
    cout << fullName << endl;

    string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    cout << "The length of the txt string is: " << txt.length() << endl;
    cout << "The length of the txt string is: " << txt.size() << endl;

    string myString = "Hello";
    cout << myString[0] << endl;
    myString[0] = 'J';
    cout << myString << endl;

    return 0;
}

结果:

John Doe
John  Doe
John Doe
The length of the txt string is: 26
The length of the txt string is: 26
H
Jello

9.1 Math(算数 cmath库)

代码示例

#include<iostream>
#include<cmath>
using namespace std;

int main(){
    cout << max(5, 10) << endl;
    cout << min(5, 10) << endl;
    cout << sqrt(64) << endl;
    cout << round(2.6) << endl;
    cout << log(2) << endl;

    cout << "abs(x)"
         << "Returns the absolute value of x" << abs(-5) << endl;
    cout << "acos(x)"
         << "Returns the arccosine of x" << acos(0.64) << endl;
    // ...
    return 0;
}

更详细的cmath库内置函数,请参阅:

https://www.w3cschool.cn/cpp/cpp-numbers.html

10.1 Condition(条件语句 if/else if/else、三目运算)

#include<iostream>
#include<cmath>
using namespace std;

int main(){
    if (20 > 18){
        cout << "20 is greater than 18" << endl;
    }

    int time = 20;

    if (time < 18){
        cout << "Good day." << endl;
    } else {
        cout << "Good evening." << endl;
    }

    if (time < 10){
        cout << "Good morning." << endl;
    } else if (time < 20){
        cout << "Good day." << endl;
    } else {
        cout << "Good evening." << endl;
    }

简单写法:三目运算///
    string result = (time < 18) ? "Good day." : "Good evening.";
    cout << result << endl;

    return 0;
}

11.1 Switch

#include <iostream>
using namespace std;

int main(){
    int day = 4;
    switch (day){
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        case 6:
            cout << "Saturday" << endl;
            break;
        case 7:
            cout << "Sunday" << endl;
            break;
        default:
            cout << "Looking forward to the Weekend" << endl;
    }
    return 0;
}

11.2 Switch

#include <iostream>
using namespace std;

int main(){
    int day = 4;
    // switch (day){
    //     case 1:
    //         cout << "Monday" << endl;
    //         break;
    //     case 2:
    //         cout << "Tuesday" << endl;
    //         break;
    //     case 3:
    //         cout << "Wednesday" << endl;
    //         break;
    //     case 4:
    //         cout << "Thursday" << endl;
    //         break;
    //     case 5:
    //         cout << "Friday" << endl;
    //         break;
    //     case 6:
    //         cout << "Saturday" << endl;
    //         break;
    //     case 7:
    //         cout << "Sunday" << endl;
    //         break;
    //     default:
    //         cout << "Looking forward to the Weekend" << endl;
    // }
    switch (day){
        case 6:
            cout << "Today is Saturday" << endl;
            break;
        case 7:
            cout << "Today is Sunday" << endl;
            break;
        default:
            cout << "Looking forward to the Weekend" << endl;
    }
    return 0;
}

12.1 Loop(循环语句 while、do…while、for)

#include<iostream>
using namespace std;

int main(){
    int i = 0;
    while (i < 5){
        cout << i << endl;
        i++;
    }

    i = 0;
    do {
        cout << i << endl;
        i++;
    } while (i < 5);

    for (int i = 0; i < 5; i++){
        cout << i << endl;
    }

    for (int i = 0; i < 10; i++){
        if (i == 4){
            continue;
        }
        cout << i << endl;
    }
    return 0;
}

13.1 Array(数组)

#include<iostream>
#include<string>
using namespace std;

int main(){
    string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; // array of strings
    string bands[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};    // size of array is 5
    int myNum[3] = {10, 20, 30};    // array of integers

    cout << cars[0] << endl;

    for (int i = 0; i < 4; i++){
        cout << i << ": " << cars[i] << endl;
    }
    return 0;
}

14.1 Reference(引用)

定义

引用变量是一个别名,也就是说,它是某个已存在变量的另一个名字。一旦把引用初始化为某个变量,就可以使用该引用名称或变量名称来指向变量。

引用与指针
引用很容易与指针混淆,它们之间有三个主要的不同:

  • 不存在空引用。引用必须连接到一块合法的内存。
  • 一旦引用被初始化为一个对象,就不能被指向到另一个对象。指针可以在任何时候指向到另一个对象。
  • 引用必须在创建时被初始化。指针可以在任何时间被初始化。

代码示例

#include <iostream>
using namespace std;

int main(){
    string food = "Pizza";
    string &meal = food;	//等价写法string& meal = food;

    cout << "food value: " << food << endl;
    cout << "meal value: " << meal << endl;
    cout << "food address: " << &food << endl;
    cout << "meal address: " << &meal << endl;

    meal = "Hamburger";
    cout << "food value: " << food << endl;
    cout << "meal value: " << meal << endl;
    cout << "food address: " << &food << endl;
    cout << "meal address: " << &meal << endl;

    return 0;
}

输出:

food value: Pizza
meal value: Pizza
food address: 0x61fde0
meal address: 0x61fde0
food value: Hamburger
meal value: Hamburger
food address: 0x61fde0
meal address: 0x61fde0

分析与解释
这段代码定义了一个字符串变量food,然后定义了另一个字符串引用变量meal,meal被初始化为food的值,因此meal和food指向同一个内存空间。最后,程序输出了food和meal的值和地址,然后将meal的值改为"Hamburger"。
可以看到,meal的值改变后,food的值也随之改变,这是因为meal是food的引用,改变meal的值就相当于改变了food的值。因此,引用变量可以在不改变内存地址的情况下修改原变量的值,这也是引用的一个重要特点。

关于引用的更多细节可以参考:

14.2 Pointer(指针)

定义

代码示例

#include<iostream>
using namespace std;

int main(){
    string food = "Pizza";
    string* ptr = &food;

    cout << "food value: " << food << endl;         // Pizza
    cout << "ptr value: " << ptr << endl;           // 0x61fde0
    cout << "food address: " << &food << endl;      // 0x61fde0
    cout << "ptr address: " << &ptr << endl;        // 0x61fdd8
    cout << "ptr dereferenced: " << *ptr << endl;   // Pizza

    // change the value of the pointer
    *ptr = "Hamburger";
    cout << "food value: " << food << endl;         // Hamburger
    cout << "ptr value: " << ptr << endl;           // 0x61fde0
    cout << "food address: " << &food << endl;      // 0x61fde0
    cout << "ptr address: " << &ptr << endl;        // 0x61fdd8
    cout << "ptr dereferenced: " << *ptr << endl;   // Hamburger

    return 0;
}

输出

food value: Pizza
ptr value: 0x61fde0
food address: 0x61fde0
ptr address: 0x61fdd8
ptr dereferenced: Pizza
food value: Hamburger
ptr value: 0x61fde0
food address: 0x61fde0
ptr address: 0x61fdd8
ptr dereferenced: Hamburger

该代码演示了指针的基本用法。
首先定义了一个字符串变量food,并将其赋值为"Pizza",然后定义一个指向字符串的指针ptr,并将其指向food变量的地址。然后分别打印出food、ptr、food的地址和ptr的地址,以及ptr所指的内容。
接下来,代码将指针ptr所指的内容修改为"Hamburger",然后再次打印出food、ptr、food的地址和ptr的地址,以及ptr所指的内容。
可以看到,指针ptr的值所指向的变量food的地址,可以通过取地址符&获取变量的地址,可以通过解引用符*获取指针所指的内容。指针和所指向的变量之间是密切相关的,修改指针所指的内容其实就是修改了所指向的变量的值。
在看一遍代码吧!代码中变量值变量地址指针存放的内容指针的地址指针所指的内容非常清晰明确!
简单理解,不过是指针中存放着变量的地址指针所指的内容是变量的值罢了。

更多资料请参考:

one more thing:对于int* x的理解

在函数声明时的int* x和函数调用中的x的符号用法是不同的。

在函数声明中的int* x表示x是一个指针变量,它指向一个整数类型的值。这是一种常见的指针声明方式。在函数声明中,*符号用于指示该变量是一个指针。

在函数调用中的x表示解引用操作符,用于获取指针x所指向的值。通过x,你可以访问指针所指向的实际值。

以下是一个示例,说明两者的不同:

void foo(int* x);  // 函数声明,参数是一个整数指针

int main() {
    int num = 10;
    int* ptr = &num;  // ptr是一个指向整数的指针,指向num的地址

    foo(ptr);  // 函数调用,将指针ptr传递给函数

    return 0;
}

void foo(int* x) {
    int value = *x;  // 解引用指针x,获取指针所指向的值
    // 其他操作...
}

15.1 Function(函数)

#include<iostream>
using namespace std;

void myFunction(){ // void means that the function does not have a return value
    cout<<"I just got executed"<<endl;
}

int main(){ //int means that the function returns an integer value
    myFunction();   //function call
    myFunction();
    myFunction();
    return 0;
}

15.2 Function(函数 函数声明)

#include<iostream>
using namespace std;

// 函数声明
void myFunction();

// 主函数
int main()
{
    myFunction(); // 函数调用
    return 0;
}

// 函数定义
void myFunction()
{
    cout << "I just got executed!";
}

15.3 Function(函数 参数传递)

#include<iostream>
using namespace std;

void myFunction(string fname){
    cout<<fname<<" Refsnes\n";
}

int main(){
    myFunction("Liam");
    myFunction("Jenny");
    myFunction("Anja");
    return 0;
}

15.4 Function(函数 参数传递默认值)

#include<iostream>
using namespace std;

void myFunction(string fname = "Anders"){
    cout<<fname<<" Refsnes\n";
}

int main(){
    myFunction("Liam");
    myFunction("Jenny");
    myFunction();
    myFunction("Anja");
    return 0;
}

15.5 Function(函数 多变量)

#include<iostream>
using namespace std;

void myFunction(string fname,int age){
    cout<<fname<<" Refsnes. "<<age<<" years old. \n";
}

int main(){
    myFunction("Liam",3);
    myFunction("Jenny",14);
    myFunction("Anja",30);
    return 0;
}

15.6 Function(函数 )

#include<iostream>
using namespace std;

int myFunction(int x, int y){
    return x + y;
}

int main(){
    cout << myFunction(5, 3) << endl;

    int z = myFunction(5, 3);
    cout << z << endl;

    return 0;
}

15.7 Function(函数 传参:值传递和引用传递 swap函数)

#include<iostream>
using namespace std;

void swap1(int x, int y){
    int temp = x;
    x = y;
    y = temp;
}

void swap2(int &x, int &y){
    int temp = x;
    x = y;
    y = temp;
}

int main(){
    int first = 10;
    int second = 20;

    cout << "Before swap1: " << first << " " << second << endl;
    swap1(first, second);
    cout << "After swap1: " << first << " " << second << endl;
    
    swap2(first, second);
    cout << "After swap2: " << first << " " << second << endl;
    return 0;
}

在C++中,函数参数传递可以通过值传递(by value)或引用传递(by reference)进行。当你在调用一个函数时,你可以将参数以值的形式传递,也可以将参数的地址传递给函数,让函数通过引用来修改参数的值。
在你的代码中,swap1函数使用的是值传递,它接受两个整数参数x和y,并在函数内部进行交换。这种情况下,函数内部交换的是局部变量的值,而不会影响到main函数中的first和second。
而swap2函数使用的是引用传递,它接受两个整数的引用x和y。通过使用引用,函数可以直接修改传递给它的变量的值。当你在main函数中调用swap2时,传递的是first和second的引用,这意味着swap2函数内部的操作会直接影响到main函数中的first和second。
所以,调用swap2(&first, &second)是错误的,因为&符号用于获取变量的地址,而swap2函数期望的是引用而不是指针。正确的调用方式是直接传递变量本身,即swap2(first, second)。在函数内部,x和y将成为first和second的别名,并且通过交换它们的值来实现交换效果。

上面是值传递、引用传递的理解,下面用指针来实现swap函数

void swap3(int* x, int* y){
    int temp = *x;
    *x = *y;
    *y = temp;
}

在swap3函数中,参数x和y是指向整数的指针。通过使用指针,我们可以通过解引用操作符*来访问指针所指向的值。

在函数内部,temp变量保存了x指针所指向的值。然后,通过解引用x和y指针,并将它们的值进行交换。

要调用这个使用指针的swap2函数,你需要传递first和second的地址。这可以通过使用取地址操作符&来实现,如下所示:

swap3(&first, &second);

这样,swap3函数将接收first和second的地址,并通过指针来进行交换操作。这会影响到main函数中的first和second变量。

15.8 Function(函数 重载)

重载的定义:
函数重载是指在同一个作用域(通常是在同一个类或命名空间中)中定义多个具有相同名称但参数列表不同的函数。函数重载允许你使用相同的函数名来执行不同的操作,根据传递给函数的参数类型和数量来选择正确的函数版本。
是不是没看懂,大白话就是:多个函数可以具有相同的名字、不同的传入参数,由传入参数区分你想调用的函数。
例如,以下的两个plusFunc根据传入的数据类型不一样,都成功被调用了

#include<iostream>
using namespace std;

int plusFunc(int x, int y){
    return x + y;
}

double plusFunc(double x, double y){
    return x + y;
}

int main(){
    int myNum1 = plusFunc(8, 5);
    double myNum2 = plusFunc(4.3, 6.26);
    cout << "Int: " << myNum1 << "\n";	//Int: 13
    cout << "Double: " << myNum2;	//Double: 10.56
    return 0;
}

16.1 Class(类)

什么是OOP?

OOP (Object Oriented Programming)面向对象编程
程序化编程只指编写对数据进行操作的程序或函数;
面向对象编程是指创建同时包含数据和函数的对象

OOP优点
在这里插入图片描述

C++类和对象

在这里插入图片描述

代码实例

#include<iostream>
using namespace std;

class Car{
    public:
        string brand;   // 在类中定义的变量称为属性
        string model;
        int year;
};
int main(){
    // Create an object of Car
    Car carObj1;    // 在类中定义的对象称为实例,或者称为对象,此时才会分配内存
    carObj1.brand = "BMW";
    carObj1.model = "X5";
    carObj1.year = 1999;
    // Create another object of Car
    Car carObj2;
    carObj2.brand = "Ford";
    carObj2.model = "Mustang";
    carObj2.year = 1969;

    // Print attribute values
    cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << endl;
    cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << endl;  
    return 0;

}

16.2 Class(类 方法)

#include<iostream>
using namespace std;

class Car{
    public:
        int speed(int maxSpeed);    
        void myMethod(){    // 类中的函数叫做方法(Method)
            cout<<"Hello World";
        }
};

int Car::speed(int maxSpeed){
    return maxSpeed;
}

int main(){
    Car myObj;  // 创建对象 
    cout<<myObj.speed(200)<<endl;   // 调用对象的方法
    myObj.myMethod();   
    return 0;
}

16.3 Class(类 构造函数)

类的构造函数是一种特殊的成员函数,它用于创建对象时初始化对象的数据成员。在C++中,构造函数的名称必须与类的名称相同,且没有返回类型(不应该有void)。构造函数可以带有参数(参数列表可以为空),也可以被重载。

#include<iostream>
using namespace std;

class Car{  // The class
    public:   // Access specifier,访问修饰符
        string brand;   // Attribute,属性
        string model;   // Attribute,属性
        int year;       // Attribute,属性
        Car(string x, string y, int z); // Constructor declaration,构造函数声明
};

// Constructor definition outside the class,构造函数定义在类外
Car::Car(string x, string y, int z) {
    brand = x;
    model = y;
    year = z;
};

int main(){
    // Create Car objects and call the constructor with different values,创建Car对象并使用不同的值调用构造函数
    Car carObj1("BMW", "X5", 1999); // 注意:创建时就会调用里面的Car(string x, string y, int z)
    Car carObj2("Ford", "Mustang", 1969);

    cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << endl;
    cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << endl;
    return 0;
}

16.4 Class(类 访问范围public private)

public允许外部访问,private不允许

#include<iostream>
using namespace std;

class MyClass{
    int b;  // private by default,默认是私有的
    public: // public access specifier,公有访问说明符
        int x; // public attribute,公有属性
        int y;
    private:    // private access specifier,私有访问说明符
        int a;
};

int main(){
    MyClass myObj;
    myObj.x = 25;
    myObj.y = 50;
    // myObj.b = 100;
    // myobj.a = 200;
    cout<<myObj.x<<endl;    // allowed (public)
    cout<<myObj.y<<endl;    // allowed (public)
    // cout<<myObj.b<<endl;    // not allowed (private)
    // cout<<myObj.a<<endl;    // not allowed (private)
    return 0;
}

16.5 Class(类 访问修改私有变量)

在C++中,getter和setter是用于访问和修改私有成员变量的方法。Getter用于获取私有成员变量的当前值,而setter用于设置私有成员变量的新值。它们提供了对私有成员变量进行控制的简便方式,同时也可确保对这些成员变量的访问和修改按照类的设计进行,以确保程序的正确性和可维护性。

#include<iostream>
using namespace std;

class Employee {
    private:
        int salary;
    public:
        // Setter,功能:设置salary的值,避免直接访问私有变量
        void setSalary(int s) {
            salary = s;
        }
        // Getter,功能:获取salary的值
        int getSalary() {
            return salary;
        }

};

int main(){
    Employee emp;
    emp.setSalary(50000);
    cout << emp.getSalary();
    return 0;
}

16.6 Class(类 继承)

#include<iostream>
using namespace std;

// Base class,基类
class Vehicle {
  public:
    string brand = "Ford";
    Vehicle() {
      cout << "This is a Vehicle" << endl;
    }
};

// Derived class,派生类/继承类
class Car: public Vehicle {
  public:
    string model = "Mustang";
};

int main() {
  Car myCar;
  cout << myCar.brand << " " << myCar.model << endl;
  return 0;
}

16.7 Class(类 多继承)

#include<iostream>
using namespace std;

// Base class
class MyClass {
  public:
    void myFunction() {
      cout << "Some content in parent class." ;
    }
};

// Another base class
class MyOtherClass {
  public:
    void myOtherFunction() {
      cout << "Some content in another class." ;
    }
};

// Derived class,同时继承两个父类
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
  MyChildClass myObj;
  myObj.myFunction();
  myObj.myOtherFunction();
  return 0;
}

16.8 Class(类 protected)

private 只有自己可以用,protected 可以自己和自己的子类用,例如下面的子类就可以用:

#include<iostream>
using namespace std;

// Base class
class Employee{
    protected: // Protected access specifier,只有自己和子类可以访问
        int salary;
};

// Derived class
class Programmer: public Employee{
    public:
        int bonus;
        void setSalary(int s){
            salary = s;
        }
        int getSalary(){
            return salary;
        }
};

int main() {
    Programmer myObj;
    myObj.setSalary(50000);
    myObj.bonus = 15000;
    cout << "Salary: " << myObj.getSalary() << "\n";
    cout << "Bonus: " << myObj.bonus << "\n";
    return 0;
}

17.1 polymorphism(多态性)

在这里插入图片描述
多态是面向对象程序设计中的一个重要概念,表示对象同一个行为或方法在不同情况下的不同响应方式。具体而言,多态性指的是同一个类的不同对象在调用同一个方法时,可以表现出不同的行为。这个特点使得程序更加灵活和可扩展,也是面向对象编程的一个重要优势。

多态可以分为编译时多态和运行时多态。编译时多态主要包括函数重载和运算符重载,通过函数签名或参数的不同来区分不同的行为;而运行时多态主要通过虚函数和抽象类实现,让对象在运行期确定调用哪个版本的方法。

例如,有一个动物基类,包含了一个虚函数makeSound(),派生类Dog和Cat分别重写了这个函数,分别实现了不同的叫声。当我们在调用一个指向动物对象的指针的makeSound()方法时,实际上调用的是这个对象所属的子类的makeSound()方法,即运行时多态。这样就让代码更加灵活,可以处理不同类型的对象,而不需要为每一个对象再写相应的代码。

#include<iostream>
using namespace std;

// Base class
class Animal {
    public:
        void animalSound() {
            cout << "The animal makes a sound \n";
        }
};

// Derived class
class Pig : public Animal {
    public:
        void animalSound() {
            cout << "The pig says: wee wee \n";
        }
};

// Derived class
class Dog : public Animal {
    public:
        void animalSound() {
            cout << "The dog says: bow wow \n";
        }
};

int main() {
    Animal myAnimal;
    Pig myPig;
    Dog myDog;

    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
    return 0;
}   

18.1 File(文件 写入)

使用fstream标准库实现文件读写

#include<iostream>
#include<fstream>
using namespace std;

int main() {
    // create a file pointer
    ofstream Myfile("sample.txt");  // ofstream is used to write to a file,具体功能是:创建一个文件,如果文件已经存在,则覆盖原有文件

    // Write to the file
    Myfile << "This is me\n";
    Myfile << "This is also me\n";

    // close the file pointer
    Myfile.close();
    return 0;
}

18.2 File(文件 读取)

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
    // Create a text string, which is used to output the text file
    string myText;
    // Read from the text file
    ifstream MyReadFile("sample.txt"); 
    // Use a while loop together with the getline() function to read the file line by line
    while (getline (MyReadFile, myText)) {
        // Output the text from the file
        cout << myText << endl;
    }
    // Close the file
    MyReadFile.close();
}

19.1 Exceptions(异常处理)
异常提供了一种转移程序控制权的方式。C++ 异常处理涉及到三个关键字:try、catch、throw

throw: 当问题出现,程序通过throw抛出一个异常。
catch: 在你想要处理问题的地方,通过异常处理程序捕获异常。
try: try 块中的代码标识将被激活的特定异常。它后面允许跟着一个或多个 catch 块。

#include<iostream>
#include<fstream>
using namespace std;

int main(){
    try{
        int age = 15 ;
        if (age > 18){
            cout << "Access granted - you are old enough.";
        }else{
            throw (age);    // throw an exception
        }
    }
    catch(int myNum){
        cout << "Access denied - You must be at least 18 years old.\n";
        cout << "Age is: " << myNum << endl;
    }

    try
    {
        int age = 15;
        if (age > 18) {
            cout << "Access granted - you are old enough.";
        } else {
            throw 505;   
        }
    }
    catch(...)  // 捕获所有异常
    {
        cout << "Access denied - You must be at least 18 years old.\n";
    }
    
}

在C++中,throw关键字用于抛出异常。异常用于处理程序执行过程中出现的异常或错误条件。

当你抛出异常时,可以指定抛出的异常对象的类型。在你的情况下,throw 505;会抛出一个值为505的int类型的异常。

在C++中,异常的类型可以是任意的。当你使用throw关键字抛出一个异常时,你可以选择使用任何类型。在上面第二个例子中,异常的类型是int,而异常的值是505。

异常的类型和值的具体含义是由程序员自行定义的。在实际的应用中,程序员可以根据需要选择适当的类型和值来表示特定的异常情况。例如,505异常可能表示某种特定的错误、状态或条件。

需要注意的是,在处理异常时,你可以根据异常的类型和值来采取不同的行动。这使得程序能够根据异常的类型和值来执行适当的错误处理或恢复操作。

总结

以上是基础,更多内容我也在学QAQ

进阶:一个项目快速上手C++

未完待续
参考视频:
【用一个项目快速上手新的编程语言】
https://www.bilibili.com/video/BV1bp4y1G7MM/?spm_id_from=333.999.0.0&vd_source=15355d30d39fe89acd7ef49fef8eabb0

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值