【C++】基础知识

学习C++基础知识有关的笔记,代码借鉴了黑马的笔记
如果有不正确或者需要补充的,敬请指教



以下是本篇文章正文内容

一、基础知识

1.1 四大区

代码区,全局区,栈区,堆区

  • 代码区:存放代码,共享只读
  • 全局区:全局变量和静态变量存放于此,在程序结束后由系统释放
  • 栈区:由编译器自动分配释放,存放函数的参数值,局部变量等
    • Tip:不要返回局部变量的地址! !!
  • 堆区:由程序员分配释放,否则程序结束时由操作系统回收,在c++中主要利用new在堆区开辟内存

堆区的数据由程序员管理开辟,程序员管理释放,如果想释放堆区的数据,利用关键字delete

1.2 引用的本质

引用:引用的本质就是一个指针常量

语法: 
int &b=a;
//即称为b引用a,b是a的一个别名,
//自动转换为 int* const b = &a;指针常量是指针指向不可改,也说明为什么引用不可更改

  • 引用必须初始化
  • 在初始化后不再改变(不是不能改变值,而是不能改变指向)

引用作为函数参数值传递

//引用传递
int mySwap03(int &a , int &b){
	int temp = a;
	//内部发现ab是引用,自动帮我们转换为:*a = *b;
	a = b;
	b = temp;
}

mySwap03(a,b); //引用传递,形参会修饰实参的

引用作为函数返回值

  1. 不要返回局部变量的引用
  2. 函数的调用可以作为左值

若一个函数的返回值是引用,可以作为等号的左值使用,从而改变函数返回的值

//返回静态变量引用
int& test02() {
    static int a = 20;
    return a;
}

//如果函数做左值,那么必须返回引用
int main() {
    int& ref2 = test02();
    cout << "ref2 = " << ref2 << endl;
    cout << "ref2 = " << ref2 << endl;

    test02() = 1000;
	//static变量a被赋值为1000,而ref2是a的别名,所以打印1000
    cout << "ref2 = " << ref2 << endl;
}

常量引用

作用:常量引用主要用来修饰形参,防止误操作导致传入的外界变量被修改

在函数形参列表中,可以加const修饰形参,防止形参改变实参

//引用使用的场景,通常用来修饰形参
void showValue(const int& v) {
    //v += 10;
    cout << v << endl;
}

int main() {
    //int& ref = 10;  引用本身需要一个合法的内存空间,因此这行错误
    //加入const之后,编译器优化代码为:int temp = 10; const int& ref = temp;
    const int& ref = 10;
    //ref = 100;  //加入const后不可以修改变量
    cout << ref << endl;

    //函数中利用常量引用防止误操作修改实参,即防止修改a
    int a = 10;
    showValue(a);
    system("pause");
    return 0;
}

1.2 函数

1.2.1 函数默认参数

在C++中,函数的形参列表中的形参是可以有默认值的。

语法:
返回值类型 函数名 (参数= 默认值){}
  1. 如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
  2. 如果函数声明有默认值,函数实现的时候就不能有默认参数。因为可能出现二义性。
int func(int a, int b = 10, int c = 10) {
    return a + b + c;
}

int func2(int a = 10, int b = 10);
int func2(int a, int b) {
    return a + b;
}

1.2.2 函数占位参数

C++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置

语法: 
返回值类型 函数名 (数据类型){}
//函数占位参数 ,占位参数也可以有默认参数
void func(int a, int) {
    cout << "this is func" << endl;
}

int main() {
    func(10,10); //占位参数必须填补
    system("pause");
    return 0;
}

1.2.3 函数重载

作用:函数名可以相同,提高复用性

函数重载满足条件:

  • 同一个作用域下
  • 函数名称相同
  • 函数参数类型不同 或者 个数不同 或者 顺序不同

注意: 函数的返回值类型不同 不可以作为函数重载的条件

1.2.4 函数重载注意事项

  • 引用作为重载条件
  • 函数重载碰到函数默认参数
//函数重载注意事项
//1、引用作为重载条件
void func(int &a)
{
    cout << "func (int &a) 调用 " << endl;
}
void func(const int &a)
{
    cout << "func (const int &a) 调用 " << endl;
}

//2、函数重载碰到函数默认参数
void func2(int a, int b = 10)
{
    cout << "func2(int a, int b = 10) 调用" << endl;
}
void func2(int a)
{
    cout << "func2(int a) 调用" << endl;
}

int main() {

    int a = 10;
    func(a); //调用无const
    func(10);//调用有const

    //func2(10); //碰到默认参数产生歧义,即默认参数也是可以用func2(10)调用,需要避免
    system("pause");
    return 0;
}

1.3 static局部静态变量

在局部变量前加上static关键字,就成了静态局部变量。
静态局部变量存放在内存的全局数据区

  • 为静态局部变量赋初值是在编译时进行值的,即只赋初值一次,在程序运行时它已有初值。
  • 函数结束时,静态局部变量不会消失,每次该函数调用时,也不会为其重新分配空间。它始终驻留在全局数据区,直到程序运行结束。静态局部变量的初始化与全局变量类似.
  • 如果不为其显式初始化,则C++自动为其初始化为0。
  • 静态局部变量与全局变量共享全局数据区,但静态局部变量只在定义它的函数中可见。
  • 静态局部变量与局部变量在存储位置上不同,使得其存在的时限也不同,导致对这两者操作的运行结果也不同。

二、 类和对象

C++面向对象的三大特性为:封装、继承、多态

C++认为万事万物都皆为对象,对象上有其属性和行为

2.1 封装

封装的意义:

  • 将属性和行为作为一个整体,表现生活中的事物
  • 将属性和行为加以权限控制

访问权限有三种:

  • public 公共权限:类内可以访问 类外可以访问
  • protected 保护权限:类内可以访问 类外不可以访问
  • private 私有权限:类内可以访问 类外不可以访问

2.1.1 class和struct的区别

在C++中 struct和class唯一的区别就在于 默认的访问权限不同
区别:

  • struct 默认权限为公共
  • class 默认权限为私有

2.1.2 构造/析构函数

编译器提供的构造函数和析构函数是空实现。

  • 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。
  • 析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作。
构造函数语法:
类名(){}
  1. 构造函数,没有返回值也不写void
  2. 函数名称与类名相同
  3. 构造函数可以有参数,因此可以发生重载
  4. 程序在调用对象时候会自动调用构造,无须手动调用,而且只会调用一次
析构函数语法:
 ~类名(){}
  1. 析构函数,没有返回值也不写void
  2. 函数名称与类名相同,在名称前加上符号 ~
  3. 析构函数不可以有参数,因此不可以发生重载
  4. 程序在对象销毁前会自动调用析构,无须手动调用,而且只会调用一次
class Person
{
public:
    //构造函数
    Person()
    {
        cout << "Person的构造函数调用" << endl;
    }
    //析构函数
    ~Person()
    {
        cout << "Person的析构函数调用" << endl;
    }
};
构造函数的分类及调用

两种分类方式:

  • ​按参数分为: 有参构造和无参构造
  • 按类型分为: 普通构造和拷贝构造

三种调用方式:

  • ​ 括号法
  • 显示法
  • 隐式转换法
class Person {
public:
    //无参(默认)构造函数
    Person() {
        cout << "无参构造函数!" << endl;
    }
    //有参构造函数
    Person(int a) {
        age = a;
        cout << "有参构造函数!" << endl;
    }
    //拷贝构造函数
    Person(const Person& p) {
        age = p.age;
        cout << "拷贝构造函数!" << endl;
    }
    //析构函数
    ~Person() {
        cout << "析构函数!" << endl;
    }
public:
    int age;
};

//2、构造函数的调用
//调用无参构造函数
void test01() {
    Person p; //调用无参构造函数
}

//调用有参的构造函数
void test02() {
    //2.1  括号法,常用
    Person p1(10);
    //注意1:调用无参构造函数不能加括号,如果加了编译器认为这是一个函数声明
    //Person p2();

    //2.2 显式法
    Person p2 = Person(10); 
    Person p3 = Person(p2);
    //Person(10)单独写就是匿名对象  当前行结束之后,马上析构

    //2.3 隐式转换法
    Person p4 = 10; // Person p4 = Person(10); 
    Person p5 = p4; // Person p5 = Person(p4); 

    //注意2:不能利用 拷贝构造函数 初始化匿名对象 编译器认为是对象声明
    //Person p5(p4);
}

构造函数调用规则如下:

  • 如果用户定义有参构造函数,c++不再提供默认无参构造,但是会提供默认拷贝构造(默认构造会进行赋值操作)
  • 如果用户定义拷贝构造函数,c++不再提供其他构造函数
拷贝构造函数调用时机

C++中拷贝构造函数调用时机通常有三种情况

  1. 使用一个已经创建完毕的对象来初始化一个新对象
  2. 值传递的方式给函数参数传值
  3. 以值方式返回局部对象
class Person {
public:
    Person() {
        cout << "无参构造函数!" << endl;
        mAge = 0;
    }
    Person(int age) {
        cout << "有参构造函数!" << endl;
        mAge = age;
    }
    Person(const Person& p) {
        cout << "拷贝构造函数!" << endl;
        mAge = p.mAge;
    }
    //析构函数在释放内存之前调用
    ~Person() {
        cout << "析构函数!" << endl;
    }
public:
    int mAge;
};

//1. 使用一个已经创建完毕的对象来初始化一个新对象
void test01() {
    Person man(100); //p对象已经创建完毕
    Person newman(man); //调用拷贝构造函数
    Person newman2 = man; //拷贝构造

	//创建时直接赋值才是拷贝构造
    //Person newman3;
    //newman3 = man; //不是调用拷贝构造函数,赋值操作
}

//2. 值传递的方式给函数参数传值
//相当于Person p1 = p;也即是值传递是创建副本,实参不会修饰形参,p1调用了自己的拷贝构造函数
void doWork(Person p1) {}
void test02() {
    Person p; //无参构造函数
    doWork(p);
}

//3. 以值方式返回局部对象
Person doWork2(){
    Person p1;
    cout << (int *)&p1 << endl;
    return p1;
}
void test03(){
	//这里执行了p的拷贝构造函数
    Person p = doWork2();
    cout << (int *)&p << endl;
}


int main() {
    //test01();
    //test02();
    test03();
    system("pause");
    return 0;
}
深拷贝/浅拷贝
  • 浅拷贝:简单的赋值拷贝操作,就是将多个类的指针指向了同一个地址
  • 深拷贝:在堆区重新申请空间,进行拷贝操作,将每个类的值重新申请空间,避免了内存重复释放问题

浅拷贝带来的问题就是堆区内存重复释放,需要深拷贝来解决

class Person {
public:
    //有参构造函数
    Person(int age ,int height) {
        cout << "有参构造函数!" << endl;
        m_age = age;
        m_height = new int(height);
    }
    
    //拷贝构造函数 (深拷贝) 
    Person(const Person& p) {
        cout << "拷贝构造函数!" << endl;
        //如果不利用深拷贝在堆区创建新内存,会导致浅拷贝带来的重复释放堆区问题
        m_age = p.m_age;
        // m_height = p.m_height; //此代码为浅拷贝代码,只是将p.m_height的所指向的地址值赋值给左边,这也是默认拷贝构造函数的代码
 
        m_height = new int(*p.m_height);
    }

    //析构函数
    ~Person() {
        cout << "析构函数!" << endl;
        if (m_height != NULL){
            delete m_height;
        }
    }
public:
    int m_age;
    int* m_height;
};

初始化列表

作用:C++提供了初始化列表语法,用来初始化属性

语法:
构造函数():属性1(1),属性2(值2... {}

示例

class Person {
public:
    传统方式初始化
    //Person(int a, int b, int c) {
    //    m_A = a;
    //    m_B = b;
    //    m_C = c;
    //}

    //初始化列表方式初始化
    Person(int a, int b, int c) :m_A(a), m_B(b), m_C(c) {}
    void PrintPerson() {
        cout << "mA:" << m_A << endl;
        cout << "mB:" << m_B << endl;
        cout << "mC:" << m_C << endl;
    }
private:
    int m_A;
    int m_B;
    int m_C;
};

2.1.3 static静态成员

静态成员就是在成员变量和成员函数前加上关键字static,称为静态成员
静态成员分为:

  • 静态成员变量
    • 所有对象共享同一份数据
    • 在编译阶段分配内存
    • 类内声明,类外初始化
  • 静态成员函数
    • 所有对象共享同一个函数
    • 静态成员函数只能访问静态成员变量,不能访问非静态成员变量

静态函数有两种访问方式:通过对象访问,通过类名访问

class Person{
public:
    static int m_A; //静态成员变量
    //静态成员变量特点:
    //1 在编译阶段分配内存
    //2 类内声明,类外初始化
    //3 所有对象共享同一份数据
private:
    static int m_B; //静态成员变量也是有访问权限的
};
int Person::m_A = 10;
int Person::m_B = 10;

void test01()
{
    //静态成员变量两种访问方式

    //1、通过对象
    Person p1;
    p1.m_A = 100;
    cout << "p1.m_A = " << p1.m_A << endl;

    Person p2;
    p2.m_A = 200;
    cout << "p1.m_A = " << p1.m_A << endl; //共享同一份数据
    cout << "p2.m_A = " << p2.m_A << endl;

    //2、通过类名
    cout << "m_A = " << Person::m_A << endl;

    //cout << "m_B = " << Person::m_B << endl; //私有权限访问不到
}

2.2 C++对象模型和this指针

2.2.1 成员变量和成员函数分开存储

在C++中,类内的成员变量和成员函数分开存储
只有非静态成员变量才属于类的对象上

class Person {
public:
    Person() {
        mA = 0;
    }
    //非静态成员变量占对象空间
    int mA;
    //静态成员变量不占对象空间
    static int mB; 
    //函数也不占对象空间,所有函数共享一个函数实例
    void func() {
        cout << "mA:" << this->mA << endl;
    }
    //静态成员函数也不占对象空间
    static void sfunc() {
    }
};

2.2.2 this指针

每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码。
那么问题是:这一块代码是如何区分那个对象调用自己的呢?
c++通过提供特殊的对象指针,this指针,解决上述问题。this指针指向被调用的成员函数所属的对象

this指针的用途:

  • 当形参和成员变量同名时,可用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可使用return *this
class Person{
public:
    Person(int age){
        //1、当形参和成员变量同名时,可用this指针来区分
        this->age = age;
    }
	//返回引用类型的原因是为了方便链式编程,如下所用
    Person& PersonAddPerson(Person p){
        this->age += p.age;
        //返回对象本身
        return *this;
    }

    int age;
};

void test01(){
    Person p1(10);
    cout << "p1.age = " << p1.age << endl;

    Person p2(10);
    //如果返回的是Person值,则会返回副本,而不是p2本身
    p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p1);
    cout << "p2.age = " << p2.age << endl;
}

2.2.3 const修饰成员函数

常函数:

  • 成员函数后加const后我们称为这个函数为常函数
  • 常函数内不可以修改成员属性
  • 成员属性声明时加关键字mutable后,在常函数中依然可以修改

常对象:

  • 声明对象前加const称该对象为常对象
  • 常对象只能调用常函数
class Person {
public:
    Person() {
        m_A = 0;
        m_B = 0;
    }

    //this指针的本质是一个指针常量,指针的指向不可修改,
    //Type* const pointer;
    //如果想让指针指向的值也不可以修改,需要声明常函数
    void ShowPerson() const {
        //在成员函数后加const等同于const Type* const pointer;
        //this = NULL; //不能修改指针的指向 Person* const this;
        //this->mA = 100; //但是this指针指向的对象的数据是可以修改的

        //const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量
        this->m_B = 100;
    }

    void MyFunc() const {
        //mA = 10000;
    }
public:
    int m_A;
    mutable int m_B; //mutable修饰,可修改 可变的
};

//const修饰对象  常对象
void test01() {

    const Person person; //常量对象  
    cout << person.m_A << endl;
    //person.mA = 100; //常对象不能修改成员变量的值,但是可以访问
    person.m_B = 100; //但是常对象可以修改mutable修饰成员变量

    //常对象访问成员函数
    person.MyFunc(); //常对象不能调用const的函数
}

int main() {
    test01();
    system("pause");
    return 0;
}

2.3 友元

友元的目的就是让一个函数或者类 访问另一个类中私有成员

友元的关键字为 friend

友元的三种实现

  1. 全局函数做友元
  2. 类做友元
  3. 成员函数做友元

2.3.1 全局函数做友元

class Building
{
    //告诉编译器 goodGay全局函数 是 Building类的好朋友,可以访问类中的私有内容
    friend void goodGay(Building * building);

public:
    Building()
    {
        this->m_SittingRoom = "客厅";
        this->m_BedRoom = "卧室";
    }


public:
    string m_SittingRoom; //客厅
private:
    string m_BedRoom; //卧室
};


void goodGay(Building * building){
    cout << "好基友正在访问: " << building->m_SittingRoom << endl;
    cout << "好基友正在访问: " << building->m_BedRoom << endl;
}


void test01(){
    Building b;
    goodGay(&b);
}

int main(){
    test01();
    system("pause");
    return 0;
}

2.3.2 类做友元

class Building;//先声明类
class goodGay{
public:
	goodGay();
    void visit();

private:
    Building *building;
};

class Building{
    //告诉编译器 goodGay类是Building类的好朋友,可以访问到Building类中私有内容
    friend class goodGay;
public:
    Building();

public:
    string m_SittingRoom; //客厅
private:
    string m_BedRoom;//卧室
};

Building::Building(){
    this->m_SittingRoom = "客厅";
    this->m_BedRoom = "卧室";
}

goodGay::goodGay(){
    building = new Building;
}

void goodGay::visit(){
    cout << "好基友正在访问" << building->m_SittingRoom << endl;
    cout << "好基友正在访问" << building->m_BedRoom << endl;
}

void test01(){
    goodGay gg;
    gg.visit();

}

int main(){
    test01();
    system("pause");
    return 0;
}

2.2.3 成员函数做友元

class Building;
class goodGay{
public:
    goodGay();
    void visit(); //只让visit函数作为Building的好朋友,可以发访问Building中私有内容
    void visit2(); 

private:
    Building *building;
};

class Building{
    //告诉编译器  goodGay类中的visit成员函数 是Building好朋友,可以访问私有内容
    friend void goodGay::visit();

public:
    Building();

public:
    string m_SittingRoom; //客厅
private:
    string m_BedRoom;//卧室
};

Building::Building(){
    this->m_SittingRoom = "客厅";
    this->m_BedRoom = "卧室";
}

goodGay::goodGay(){
    building = new Building;
}

void goodGay::visit(){
    cout << "好基友正在访问" << building->m_SittingRoom << endl;
    cout << "好基友正在访问" << building->m_BedRoom << endl;
}

void goodGay::visit2(){
    cout << "好基友正在访问" << building->m_SittingRoom << endl;
    //cout << "好基友正在访问" << building->m_BedRoom << endl;
}

void test01(){
    goodGay  gg;
    gg.visit();

}

int main(){
    test01();
    system("pause");
    return 0;
}

2.4 运算符重载

运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

2.4.1 加号运算符重载

作用:实现两个自定义数据类型相加的运算
实例:两种实现:1. 成员函数重载+。2. 全局函数重载+

class Person {
public:
    Person() {};
    Person(int a, int b){
        this->m_A = a;
        this->m_B = b;
    }
    //成员函数实现 + 号运算符重载
    Person operator+(const Person& p) {
        Person temp;
        temp.m_A = this->m_A + p.m_A;
        temp.m_B = this->m_B + p.m_B;
        return temp;
    }

public:
    int m_A;
    int m_B;
};

//全局函数实现 + 号运算符重载
//Person operator+(const Person& p1, const Person& p2) {
//    Person temp(0, 0);
//    temp.m_A = p1.m_A + p2.m_A;
//    temp.m_B = p1.m_B + p2.m_B;
//    return temp;
//}

//运算符重载 可以发生函数重载 
Person operator+(const Person& p2, int val) {
    Person temp;
    temp.m_A = p2.m_A + val;
    temp.m_B = p2.m_B + val;
    return temp;
}

//测试函数
void test() {
    Person p1(10, 10);
    Person p2(20, 20);

    //成员函数方式
    Person p3 = p2 + p1;  //相当于调用 p2.operaor+(p1)
    cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;

    Person p4 = p3 + 10; //相当于调用 operator+(p3,10)
    cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;
}

int main() {
    test();
    system("pause");
    return 0;
}

2.4.2 左移运算符重载

作用:可以输出自定义数据类型

重载左移运算符配合友元可以实现输出自定义数据类型

class Person {
    friend ostream& operator<<(ostream& out, Person& p);
public:
    Person(int a, int b){
        this->m_A = a;
        this->m_B = b;
    }

    //成员函数 实现不了  p << cout 不是我们想要的效果
    //void operator<<(Person& p){
    //}

private:
    int m_A;
    int m_B;
};
//全局函数实现左移重载
//ostream对象只能有一个,out是一个标准输出流对象
ostream& operator<<(ostream& out, Person& p) {
    out << "a:" << p.m_A << " b:" << p.m_B;
    return out;
}

void test() {
    Person p1(10, 20);
    cout << p1 << "hello world" << endl; //链式编程
}

int main() {
    test();
    system("pause");
    return 0;
}

2.4.3 自增运算符重载

作用: 通过重载递增运算符,实现自己的整型数据

class MyInteger {

    friend ostream& operator<<(ostream& out, MyInteger myint);

public:
    MyInteger() {
        m_Num = 0;
    }
    //前置++
    MyInteger& operator++() {
        //先++
        m_Num++;
        //再返回
        return *this;
    }

    //后置++
    //int是一个占位参数,可以用来区分前置/后置++
    MyInteger operator++(int) {
        MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
        m_Num++;
        return temp;
    }

private:
    int m_Num;
};


ostream& operator<<(ostream& out, MyInteger myint) {
    out << myint.m_Num;
    return out;
}

//前置++ 先++ 再返回
void test01() {
    MyInteger myInt;
    cout << ++myInt << endl;
    cout << myInt << endl;
}

//后置++ 先返回 再++
void test02() {
    MyInteger myInt;
    cout << myInt++ << endl;
    cout << myInt << endl;
}

int main() {
    test01();
    //test02();
    system("pause");
    return 0;
}

2.4.4 赋值运算符重载

c++编译器至少给一个类添加4个函数

  • 默认构造函数(无参,函数体为空)
  • 默认析构函数(无参,函数体为空)
  • 默认拷贝构造函数,对属性进行值拷贝
  • 赋值运算符 operator=,对属性进行值拷贝

如果类中有属性指向堆区(即包含指针),做赋值操作时也会出现深浅拷贝问题。

针对以下情况,需要显式地提供赋值运算符重载函数(即自定义赋值运算符重载函数):

  • 用非类“A”类型的值为类“A”的对象赋值时(当然,这种情况下我们也可以不提供相应的赋值运算符重载函数,而只提供相应的构造函数);
  • 用类“A”类型的值为类“A”的对象赋值,且类“A”的数据成员中含有指针的情况下,必须显式提供赋值运算符重载函数。
class Person{
public:

    Person(int age){
        //将年龄数据开辟到堆区
        m_Age = new int(age);
    }

    //重载赋值运算符 
    Person& operator=(Person &p){
        if (m_Age != NULL){
            delete m_Age;
            m_Age = NULL;
        }
        //编译器提供的代码是浅拷贝
        //m_Age = p.m_Age;

        //提供深拷贝 解决浅拷贝的问题
        m_Age = new int(*p.m_Age);

        //返回自身
        return *this;
    }
    ~Person(){
        if (m_Age != NULL){
            delete m_Age;
            m_Age = NULL;
        }
    }
    //年龄的指针
    int *m_Age;

};

void test01(){
    Person p1(18);
    Person p2(20);
    Person p3(30);

    p3 = p2 = p1; //赋值操作
    cout << "p1的年龄为:" << *p1.m_Age << endl;
    cout << "p2的年龄为:" << *p2.m_Age << endl;
    cout << "p3的年龄为:" << *p3.m_Age << endl;
}

int main() {
    test01();
    system("pause");
    return 0;
}

下方语句1和语句2在调用函数时是有区别的:
语句1:是对象myInt02t的声明及定义,调用类MyInter的无参构造函数,所以“myInt02 = myInt;”一句是在对象myInt已经存在的情况下,用myInt来为myInt02赋值,调用的是赋值运算符重载函数
语句2:是用myInt来初始化myInt02,调用的是拷贝构造函数。拷贝构造函数的语句样式为“MyInter(const MyInt& tem)”。

//语句1
MyInter myInt02;
myInt02 = myInt;

//语句2
MyInter myInt02 = myInt;

2.4.5 关系运算符重载

作用:重载关系运算符,可以让两个自定义类型对象进行对比操作

class Person{
public:
    Person(string name, int age){
        this->m_Name = name;
        this->m_Age = age;
    };

	//==号运算符重载,返回bool类型
    bool operator==(Person & p){
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age){
            return true;
        }
        return false;
    }
	//!=号运算符重载,返回bool类型
    bool operator!=(Person & p){
        if (this->m_Name == p.m_Name && this->m_Age == p.m_Age){
            return false;
        }
 		return true;
    }

    string m_Name;
    int m_Age;
};

void test01(){
    Person a("孙悟空", 18);
    Person b("孙悟空", 18);
    if (a == b){
        cout << "a和b相等" << endl;
    }
    else{
        cout << "a和b不相等" << endl;
    }

    if (a != b){
        cout << "a和b不相等" << endl;
    }
    else{
        cout << "a和b相等" << endl;
    }
}

int main() {
    test01();
    system("pause");
    return 0;
}

2.4.6 函数调用运算符重载

函数调用运算符 () 也可以重载

  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活
class MyPrint{
public:
    void operator()(string text){
        cout << text << endl;
    }

};
void test01(){
    //重载的()操作符 也称为仿函数
    MyPrint myFunc;
    myFunc("hello world");
}


class MyAdd{
public:
    int operator()(int v1, int v2){
        return v1 + v2;
    }
};

void test02(){
    MyAdd add;
    int ret = add(10, 10);
    cout << "ret = " << ret << endl;

    //匿名对象调用  
    cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main() {
    test01();
    test02();
    system("pause");
    return 0;
}

2.5 继承

class A : public B{
	类体
};

A 类称为子类 或 派生类
B 类称为父类 或 基类

2.5.1 继承方式

继承方式一共有三种:

  1. 公共继承
  2. 保护继承
  3. 私有继承
    继承方式

父类中私有成员也是被子类继承下去了,只是由编译器给隐藏后访问不到

class Base1{
public: 
    int m_A;
protected:
    int m_B;
private:
    int m_C;
};

//公共继承
class Son1 :public Base1{
public:
    void func(){
        m_A; //可访问 public权限
        m_B; //可访问 protected权限
        //m_C; //不可访问
    }
};

void myClass(){
    Son1 s1;
    s1.m_A; //其他类只能访问到公共权限
}

//保护继承
class Base2{
public:
    int m_A;
protected:
    int m_B;
private:
    int m_C;
};
class Son2:protected Base2{
public:
    void func(){
        m_A; //可访问 protected权限
        m_B; //可访问 protected权限
        //m_C; //不可访问
    }
};
void myClass2(){
    Son2 s;
    //s.m_A; //不可访问
}

//私有继承
class Base3{
public:
    int m_A;
protected:
    int m_B;
private:
    int m_C;
};
class Son3:private Base3{
public:
    void func(){
        m_A; //可访问 private权限
        m_B; //可访问 private权限
        //m_C; //不可访问
    }
};
class GrandSon3 :public Son3{
public:
    void func() {
        //Son3是私有继承,所以继承Son3的属性在GrandSon3中都无法访问到
        //m_A;
        //m_B;
        //m_C;
    }
};

2.5.2 继承中构造和析构顺序

子类继承父类后,当创建子类对象,也会调用父类的构造函数。
继承中 先调用父类构造函数,再调用子类构造函数,析构顺序与构造相反。
这和在类中创建另一个类的对象时,构造/析构函数调用顺序相同。

2.5.3 子父类同名成员处理方式

问题:当子类与父类出现同名的成员,如何通过子类对象,访问到子类或父类中同名的数据呢?

  • 访问子类同名成员 直接访问即可
  • 当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类中同名函数
//父类
class Base {
public:
    Base(){
        m_A = 100;
    }
    void func(){
        cout << "Base - func()调用" << endl;
    }
    void func(int a){
        cout << "Base - func(int a)调用" << endl;
    }

public:
    int m_A;
};

//子类继承父类
class Son : public Base {
public:
    Son(){
        m_A = 200;
    }

    //当子类与父类拥有同名的成员函数,子类会隐藏父类中所有版本的同名成员函数
    //如果想访问父类中被隐藏的同名成员函数,需要加父类的作用域
    void func(){
        cout << "Son - func()调用" << endl;
    }
public:
    int m_A;
};
//测试函数
void test01(){
    Son s;

    cout << "Son下的m_A = " << s.m_A << endl;
    //调用s的父类函数,需要加作用域,即父类类名Base
    cout << "Base下的m_A = " << s.Base::m_A << endl;

    s.func();
    s.Base::func();
    s.Base::func(10);
}
int main() {
    test01();
    system("pause");
    return EXIT_SUCCESS;
}

2.5.4 多继承语法

C++允许一个类继承多个类

语法:
class 子类 :继承方式 父类1 , 继承方式 父类2...{
	类体
}

多继承可能会引发父类中有同名成员出现,需要加作用域区分
C++实际开发中不建议用多继承

2.5.5 菱形继承问题(虚继承解决,原理还有待补充)

菱形继承概念:两个派生类继承同一个基类 又有某个类同时继承者两个派生类。​这种继承被称为菱形继承,或者钻石继承。

菱形继承问题
菱形继承问题:

  • 羊继承了动物的数据,驼同样继承了动物的数据,当草泥马使用数据时,就会产生二义性。(比如说年龄,性别)
  • 草泥马继承自动物的数据继承了两份,其实我们应该清楚,这份数据我们只需要一份就可以。
class Animal{
public:
    int m_Age;
};

//继承前加virtual关键字后,变为虚继承
//此时公共的父类Animal称为虚基类
class Sheep : virtual public Animal {};
class Tuo   : virtual public Animal {};
class SheepTuo : public Sheep, public Tuo {};

void test01(){
    SheepTuo st;
    st.Sheep::m_Age = 100;
    st.Tuo::m_Age = 200;

    cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;
    cout << "st.Tuo::m_Age = " <<  st.Tuo::m_Age << endl;
    cout << "st.m_Age = " << st.m_Age << endl;
}

int main() {
    test01();
    system("pause");
    return 0;
}

2.3 多态

多态分为两类

  • 静态多态: 函数重载 和 运算符重载属于静态多态,复用函数名
  • 动态多态: 派生类和虚函数实现运行时多态

静态多态和动态多态区别:

  • 静态多态的函数地址早绑定 - 编译阶段确定函数地址
  • 动态多态的函数地址晚绑定 - 运行阶段确定函数地址

多态满足条件:
1、有继承关系
2、子类重写父类中的虚函数
多态使用:
父类指针或引用指向子类对象

class Animal{
public:
    //Speak函数就是虚函数
    //函数前面加上virtual关键字,变成虚函数,那么编译器在编译的时候就不能确定函数调用了。
    virtual void speak(){
        cout << "动物在说话" << endl;
    }
};

class Cat :public Animal{
public:
	//重写父类中的虚函数
    virtual void speak(){
        cout << "小猫在说话" << endl;
    }
};

class Dog :public Animal{
public:
	//重写父类中的虚函数
    virtual void speak(){
        cout << "小狗在说话" << endl;
    }
};
//我们希望传入什么对象,那么就调用什么对象的函数
//如果函数地址在编译阶段就能确定,那么静态联编
//如果函数地址在运行阶段才能确定,就是动态联编

void DoSpeak(Animal & animal){
    animal.speak();
}
//多态满足条件: 
//1、有继承关系
//2、子类重写父类中的虚函数
//多态使用:
//父类指针或引用指向子类对象
void test01(){
    Cat cat;
    DoSpeak(cat);

    Dog dog;
    DoSpeak(dog);
}

int main() {
    test01();
    system("pause");
    return 0;
}

2.3.1 多态的底层原理

如上示例中。
当在父类Aiminal中写有虚函数时,父类中便自动生成一个虚指针vfptr,指向一个虚函数表vftable。虚函数表中会记录类中各个虚函数所在的地址。

当子类继承时,也会继承这个虚指针vfptr,指向子类的虚函数表。(此虚函数表就是父类的副本)
子类中对父类的虚函数进行重写时,便会自动将副本中的虚函数进行覆盖,变成重写后的虚函数地址。而父类的虚函数表没有变化。

Tip:如果父类或者祖先类中函数speak()为虚函数,则子类及后代类中,是否加virtual关键字,speak()都将是虚函数。
为了提高程序的可读性,建议后代中虚函数都加上virtual关键字。

当父类的指针指向子类对象时,便会发生多态
如Animal & animal = cat

2.3.2 纯虚函数和抽象函数

多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数

纯虚函数语法:
virtual 返回值类型 函数名 (参数列表)= 0 ;

virtual void func() = 0;

当类中有了纯虚函数,这个类也称为抽象类
抽象类特点:

  • 无法实例化对象
  • 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
class Base{
public:
    //纯虚函数
    //类中只要有一个纯虚函数就称为抽象类
    virtual void func() = 0;
};

class Son :public Base{
public:
    virtual void func() {
        cout << "func调用" << endl;
    };
};

void test01(){
    Base * base = NULL;
    //base = new Base; // 错误,抽象类无法实例化对象
    base = new Son;
    base->func();
    delete base;//记得销毁
}

int main() {
    test01();
    system("pause");
    return 0;
}

2.3.3 虚析构和纯虚析构

多态使用时,如果子类中有属性开辟到堆区(如含有指针成员,需要在析构函数中释放),那么父类指针在释放时无法调用到子类的析构代码
Animal *animal = new Cat(“Tom”);
delete animal;//不会调用Cat的析构函数
解决方式:将父类中的析构函数改为虚析构或者纯虚析构

虚析构和纯虚析构共性:

  • 可以解决父类指针释放子类对象
  • 都需要有具体的函数实现

虚析构和纯虚析构区别:

  • 如果是纯虚析构,该类属于抽象类,无法实例化对象
虚析构语法:
virtual ~类名(){}

纯虚析构语法:
virtual ~类名() = 0;

//析构函数实现
类名::~类名(){}

虚析构/纯虚析构应用场景:

  1. 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
  2. 如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
  3. 拥有纯虚析构函数的类也属于抽象类
class Animal {
public:

    Animal()
    {
        cout << "Animal 构造函数调用!" << endl;
    }
    virtual void Speak() = 0;

    //析构函数加上virtual关键字,变成虚析构函数
    //virtual ~Animal()
    //{
    //    cout << "Animal虚析构函数调用!" << endl;
    //}
	
	//纯虚析构
    virtual ~Animal() = 0;
};

//纯虚析构函数实现
Animal::~Animal(){
    cout << "Animal 纯虚析构函数调用!" << endl;
}

//和包含普通纯虚函数的类一样,包含了纯虚析构函数的类也是一个抽象类。不能够被实例化。

class Cat : public Animal {
public:
    Cat(string name){
        cout << "Cat构造函数调用!" << endl;
        m_Name = new string(name);
    }
    virtual void Speak(){
        cout << *m_Name <<  "小猫在说话!" << endl;
    }
    ~Cat(){
        cout << "Cat析构函数调用!" << endl;
        if (this->m_Name != NULL) {
            delete m_Name;
            m_Name = NULL;
        }
    }

public:
	//子类包含了指针,空间开辟到堆区
    string *m_Name;
};

void test01(){
    Animal *animal = new Cat("Tom");
    animal->Speak();

    //通过父类指针去释放,会导致子类对象可能清理不干净,造成内存泄漏
    //怎么解决?给基类增加一个虚析构函数
    //虚析构函数就是用来解决通过父类指针释放子类对象
    delete animal;
}

int main() {
    test01();
    system("pause");
    return 0;
}

三、 文件操作

程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放
通过文件可以将数据持久化
C++中对文件操作需要包含头文件 < fstream >

文件类型分为两种:

  • 文本文件 - 文件以文本的ASCII码形式存储在计算机中
  • 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们

操作文件的三大类:

  • ofstream:写操作
  • ifstream: 读操作
  • fstream : 读写操作

3.1 文本文件

3.1.1 写文件

写文件步骤如下:

  1. 包含头文件 #include< fstream >
  2. 创建流对象 ofstream ofs;
  3. 打开文件 ofs.open(“文件路径”,打开方式);
  4. 写数据 ofs << “写入的数据”;
  5. 关闭文件 ofs.close();

文件打开方式:

打开方式 解释
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,再创建
ios::binary 二进制方式

打开方式解释
ios::in读文件
ios::out写文件
ios::ate初始位置:文件尾
ios::app追加写
ios::trunc如果文件存在先删除,再创建
ios::binary二进制方式

注意: 文件打开方式可以配合使用,利用|操作符
例如:用二进制方式写文件 ios::binary | ios:: out

#include <fstream>
void test01(){
    ofstream ofs;
    ofs.open("test.txt", ios::out);

    ofs << "姓名:张三" << endl;
    ofs << "性别:男" << endl;
    ofs << "年龄:18" << endl;

    ofs.close();
}

int main() {
    test01();
    system("pause");
    return 0;
}

3.1.2 读文件

四种方式读取

利用is_open函数可以判断文件是否打开成功

#include <fstream>
#include <string>
void test01(){
    ifstream ifs;
    ifs.open("test.txt", ios::in);
	
	//利用is_open函数可以判断文件是否打开成功
    if (!ifs.is_open()){
        cout << "文件打开失败" << endl;
        return;
    }

    //第一种方式,右移运算符
    char buf[1024] = { 0 };
    while (ifs >> buf){
        cout << buf << endl;
    }

    //第二种,利用getline()函数按行获取
    //参数分别为读取数据存储位置,以及读取大小
    char buf[1024] = { 0 };
   	  while (ifs.getline(buf,sizeof(buf))){
        cout << buf << endl;
    }

    //第三种,全局函数getline()
    //参数为,输入流对象,这里为ifs,以及存储位置
    string buf;
    while (getline(ifs, buf)){
        cout << buf << endl;
    }

	//第四种,按字符读取
    char c;
    while ((c = ifs.get()) != EOF){
        cout << c;
    }

    ifs.close();
}

int main() {
    test01();
    system("pause");
    return 0;
}

3.2 二进制文本

以二进制的方式对文件进行读写操作
打开方式为 ios::binary

3.2.1 写文件

二进制方式写文件主要利用流对象调用成员函数write

  • 函数原型 :ostream& write(const char * buffer,int len);
  • 参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

以二进制的方式写入文件的数据,打开后可能会出现乱码情况,这是正常,在读取时候正常即可。

#include <fstream>
#include <string>
class Person{
public:
    char m_Name[64];
    int m_Age;
};

//二进制文件  写文件
void test01(){
    //1、包含头文件

    //2、创建输出流对象
    ofstream ofs;
    //也可以在创建时直接打开
    //ofs.open("person.txt", ios::out | ios::binary);

    //3、打开文件
    ofs.open("person.txt", ios::out | ios::binary);

    Person p = {"张三"  , 18};

    //4、写文件
    ofs.write((const char *)&p, sizeof(p));

    //5、关闭文件
    ofs.close();
}

3.2.2 读文件

二进制方式读文件主要利用流对象调用成员函数read
函数原型:istream& read(char *buffer,int len);
参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

#include <fstream>
#include <string>

class Person{
public:
    char m_Name[64];
    int m_Age;
};

//测试函数
void test01(){
    ifstream ifs("person.txt", ios::in | ios::binary);
    if (!ifs.is_open()){
        cout << "文件打开失败" << endl;
    }
    Person p;
    ifs.read((char *)&p, sizeof(p));
    cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值