《黑马笔记》 --- C++核心编程

发布于:2025-07-16 ⋅ 阅读:(20) ⋅ 点赞:(0)

1.内存分区模型

c++在程序运行时,将内存大方向分为四个区:

  • 代码区:放代码的区域,由操作系统管理
  • 全局区:全局变量,静态变量,常量,操作系统释放
  • 栈区:局部变量,由编译器管理释放
  • 堆区:程序员自己管理的内存,若程序员不释放,则程序结束时操作系统自动回收。

1.1 程序运行前

程序运行之前有代码区全局区
在这里插入图片描述

从上图可以发现,全局和局部是分开的,虽然全区常量和全局变量,静态变量都是在全局区,但是,可以发现变量常量其实也是分开的。
在这里插入图片描述

1.2 程序运行后

程序运行之后有栈区堆区

  • 栈区:局部变量,由编译器管理释放

在这里插入图片描述

#include <iostream>

using namespace std;

//栈区主要是存放局部变量
int* fun()
{
	int a = 100;	//局部变量存放在栈中,栈区的数据在该函数结束时自动释放。

	return &a;	//ERROR千万不要返回局部变量的地址,
}


int main()
{

	int* a = fun();
	
	cout << *a << endl;
	cout << *a << endl;
	cout << *a << endl;


	return 0;
}

编译器在32位下会帮你保留一次,在64位下: 《vs2022:孩子我将永远保护你》
当函数结束时,栈中的数据也会被释放,我们再用指针操作就是非法操作
编译器会在编译的时候也会提示你,我们杜绝这种操作出现。
在这里插入图片描述

  • 堆区:程序员自己管理的内存,若程序员不释放,则程序结束时操作系统自动回收。
  • 在C++中主要利用new在堆区开辟内存,可以利用delete释放。
#include <iostream>

using namespace std;


int* fun()
{
	int* p = new int(1001000);	//new开辟出来的在堆区上,所以函数结束不会释放。

	//cout << (int)p << endl;
	return p;
}


int main()
{
	int* p = fun();


	//cout << (int)p << endl;

	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;


	return 0;		//程序结束后,new没有手动释放,则系统自动回收。
}

1.3 new的操作

new 有点像C语言学习中的malloc函数,同样都是在堆上开辟,但是,new可比malloc方便多了。

new 一个变量 
int*p = new int(赋值);
delete p;
new 一个数组 
int* arr = new int[长度];
delete[] arr;
#include <iostream>

using namespace std;

int* new1()
{
	int* p = new int(10);

	return p;
}

int* new2()
{
	int* arr = new int[10];	//开辟数组
	for (int i = 0; i < 10; i++)
		arr[i] = i;

	return arr;
}


void test1()
{
	int* p = new1();
	cout << *p << endl;
	delete p;

	//cout << *p << endl;

	int* arr = new2();
	for (int i = 0; i < 10; i++)
		cout << arr[i] << " ";

	cout << endl;

	delete[] arr;	//释放数组加[]。
}


int main()
{
	test1();
	return 0;
}

2. 引用

2.1 引用的基本语法

数据类型 &引用名称 = 变量名
int main()
{
	int a = 10;
	int& b = a;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;


	b = 10000;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	
	return 0;
}

在这里插入图片描述

2.2 引用的注意事项

  • 引用时必须初始化
int &p; !!!错误
  • 引用初始化后不可以再更改
int &b = a;
b= c; 赋值操作,不是更改引用。

2.3 引用作函数参数

函数中用引用传递,感觉tnn的比传指针NB啊,这不比指针写起来清楚啊。

#include <iostream>

using namespace std;


//传值
void mySwap01(int a, int b)
{
	int t = a;
	a = b;
	b = t;

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

}
//传址
void mySwap02(int* a, int* b)
{
	int t = *a;
	*a = *b;
	*b = t;

}
//引用传递
void mySwap03(int& a, int& b)
{
	int t = a;
	a = b;
	b = t;
}

int main()
{
	int a = 10, b = 20;
	//mySwap01(a,b);

	//mySwap02(&a, &b);


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

	mySwap03(a, b);

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


	return 0;
}

2.4引用作函数的返回值

  • 不要返回局部变量的返回值

因为函数结束时,栈区中的空间会被自动释放,你接受了一个未知的引用,再使用引用操作就会是非法操作

  • 函数的调用可以作为左值

在这里插入图片描述

因为函数的返回值是引用,返回了一个别名,这个fun() 可以看成一个别名。

#include <iostream>
using namespace std;
int& fun()
{
	static int a = 10;

	return a;
}
//int* fun2()
//{
//	static int a = 20;
//
//	return &a;
//}
int main()
{

	//引用
	int& b = fun();
	cout << b << endl;
	fun() = 100;
	cout << b << endl;

	////指针
	//int* c = fun2();
	//cout << *c << endl;
	//(*fun2()) = 200; //
	//cout << *c << endl;

	return 0;
}

2.5 引用的本质

引用的本质就是一个指针常量 那它的根基还是指针么。
讲讲指针常量常量指针的区别。

  • 指针常量:可以更改指针指向变量的值,但不能更改指针的指向。
  • 常量指针:可以更改指针的指向,但不能更改指针指向变量的值。
int*  const p = &a; //指针常量
const int* p = &a;	//常量指针 

C++中引用的本质就是指针常量,这就解释了为什么引用必须初始化,而一旦初始化后就不能更改引用了。
所以在C++中比较推荐使用引用,语法也方便。

3. 函数提高

3.1 函数默认参数

  • 可以给函数参数赋默认值, 若实参无值则用默认,实参有值则用实参

注意:

  1. 如果形参某个位置有默认参数,则其以后的所有形参都必须有默认参数
  2. 函数声明和实现只能有一个可以有默认参数
#include <iostream>

using namespace std;



int fun01(int a, int b, int c)
{
	return a + b + c;
}


//可以给函数参数赋默认值, 若实参无值则用默认,实参有值则用实参
//  注意 
//  1.如果形参某个位置有默认参数,则其以后的所有形参都必须有默认参数。
//	2.函数声明和实现只能有一个可以有默认参数。

int fun02(int a, int b = 20, int c = 30)
{
	return a + b + c;
}


int main()
{

	cout << fun01(10, 10, 10) << endl; //30

	cout << fun02(10) << endl;	// 60

	cout << fun02(10, 10) << endl;	//50

	cout << fun02(10, 10, 10) << endl;	//30

	return 0;
}

3.2 函数的占位参数

3.3 函数重载

函数重载必须满足下面三个条件

  1. 同一个作用域下
  2. 函数名称相同
  3. 函数参数类型不同,或者个数不同,或者顺序不同。
#include <iostream>

using namespace std;

//函数重载满足条件
//1.同一个作用域下
//2.函数名称相同
//3.函数参数类型不同,或者个数不同,或者顺序不同

void fun()
{
	cout << "fun()的调用" << endl;
}

void fun(int a)
{
	cout << "fun(int)的调用" << endl;
}void fun(double a)
{
	cout << "fun(double)的调用" << endl;
}void fun(int a, double b)
{
	cout << "fun(int, double)的调用" << endl;
}void fun(double a, int b)
{
	cout << "fun(double, int)的调用" << endl;
}

int main()
{
	fun();
	fun(1);
	fun(1.1);
	fun(1, 1.1);
	fun(1.1, 1);

	return 0;
}

在这里插入图片描述

3.4函数重载注意事项

  • 引用作为重载的条件
  • 函数重载碰上默认参数
#include <iostream>

using namespace std;


//函数重载的注意事项
//1. 引用作为重载的条件

void fun(int& a)
{
	cout << "fun(int &a)的调用" << endl;
}

void fun(const int& a)
{
	cout << "fun(const int &a)的调用" << endl;
}

//2. 函数重载碰上默认参数
void fun2(int a, int b = 20)
{
	cout << "fun2(int a, int b = 20)的调用" << endl;
}

void fun2(int a)
{
	cout << "fun2(int a)的调用" << endl;
}


int main()
{
	//1.
	int a = 10;
	fun(a);
	fun(10);

	fun2(10, 20)	//true
	fun2(10);		//error 出现了二义性


	return 0;
}

4. 类和对象

C++面向对象的三大特性: 封装 继承 多态。世界上的所有东西都是对象,都有属性行为
例如:

  • 人可以作为对象,属性:姓名,年龄,身高…, 行为: 说话,走路…
  • 汽车可以作为对象, 属性:方向盘,座椅… 行为: 载人,空调,放音乐。

具有相同属性的对象,我们抽象成类,人属于人类,车属于车类。

4.1 封装

封装是c++面向对象的三大特性之一,嗯。。有点像C语言中的结构体

4.1.1 封装的意义

封装的意义:

  • 将属性和行为作为一个整体。
  • 将属性和行为加以权限设置

语法:

class 类名
{
访问权限:
属性/行为
};

代码示例

#include <iostream>
#include <string>

using namespace std;

const double PI = 3.14;

//设计一个圆
class Circle
{
	//访问权限
public:	//公共权限



	//类中的属性和行为 统一成为成员
	//属性也称为 成员属性 和 成员变量
	//行为也成为 成员函数 和 成员方法
	//属性
	int m_r;	//半径


	//行为		//求周长
	double calculateZC()
	{
		return 2 * PI * m_r;
	}
};

class Student
{
public:

	string m_name;	//姓名
	int m_id;		//学号


	void SetName(string name)
	{
		m_name = name;
	}

	void SetId(int id)
	{
		m_id = id;
	}


	void ShowStudent()
	{
		cout << "姓名: " << m_name << " 学号: " << m_id << endl;
	}


};




int main()
{

	Circle c1;
	c1.m_r = 5;
	cout << "c1 的周长是: " << c1.calculateZC() << endl;

	Student s1;
	s1.SetName("kxq");
	s1.SetId(123);
	s1.ShowStudent();

	return 0;
}

封装的权限有三种:

  • 公共权限 public
  • 保护权限 protected
  • 私有权限 private
#include <iostream>

using namespace std;


//访问权限
//三种
//公共权限 public		//成员 类内可以访问 类外可以访问
//保护权限 protected	//成员 类内可以访问 类外不可以访问
//私有权限 private		//成员 类内可以访问 类外不可以访问

class Person
{
//公共权限
public:
	string m_Name;	//姓名
//保护权限
protected:
	string m_Car;	//汽车
//私有权限
private:
	int m_Password;	//银行卡密码

public:
	void fun()
	{

		m_Name = "kxq";
		m_Car = "宝马";
		m_Password = 123;
	}


};



int main()
{
	Person p1;
	p1.fun();
	//p1.m_Car = "自行车";//类外不可访问
	//p1.m_Password = 32131
	return 0;
}

4.1.2 struct 和 class的区别

struct 和 class的唯一区别就是默认访问权限不同

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

在这里插入图片描述

4.1.3 成员属性设置私用

成员属性设置私有在将来工作开发中很重要,并不是所有的数据对外界都可以可读可写。

  • 可以自己控制读写权限
  • 对于写可以检测数据的有效性

下面的代码中展示里如何控制其读写能力其中setAge()函数中有一个有效性能验证:

#include <iostream>

using namespace std;


class Person
{
	//私有成员
private:
	string m_Name;	//姓名	允许读写
	int m_Age = 21;		//年龄	允许读
	string m_Idol;	//偶像	允许写

public:
	//设置姓名				---	 写
	void setName(string name)
	{
		m_Name = name;
	}
	//获取姓名				--- 读
	string getName()
	{
		return m_Name;
	}

	//获取年龄			---读
	int getAge()
	{
		return m_Age;
	}

	
	//设置偶像			--写
	void setIdol(string Idol)
	{
		m_Idol = Idol;
	}

};






int main()
{
	Person p;
	p.setName("笑脸");
	cout << "姓名:" << p.getName() << " 年龄: " << p.getAge() << endl;
	p.setIdol("念旧N9");
	return 0;
}

4.2 对象的初始化和清理

我们日常生活中的手机,电脑都有恢复出厂设置。c++中的面向对象源于生活,每个对向都会有初始设置以及对象销毁前的清理数据的设置。

4.2.1构造函数和析构函数

  • 构造函数: 初始化
  • 析构函数: 清理销毁

如果我们不提供这两个函数,编译器会自己调用自己提供,不过两个函数都是空实现**,所以构造函数和析构函数是必须有的。**

  • 构造函数:
    1. 函数名和类名相同
    1. 可以有参数,可以发生重载
  • 析构函数:
    1. 函数名和类名相同 但是前面需要加~
    1. 不可以有参数,不可以发生重载

他俩都没有返回值,都不用写void,都是只执行一次,自动调用,构造开始,析构结束。
在这里插入图片描述

4.2.2 构造函数的分类以及调用

两种分类方式:

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

三种调用方式:

  • 括号法
  • 显示法
  • 隐式转换法
#include<iostream>

using namespace std;


class Person
{
public:
	//无参构造函数
	Person()
	{
		cout << "Person 无参构造函数的调用" << endl;
	}
	//有参构造函数
	Person(int a)
	{
		m_age = a;	
		cout << "Person 有参构造函数的调用" << endl;
	}
	//拷贝构造函数
	Person(const Person& p)
	{
		m_age = p.m_age;
		cout << "Person 拷贝构造函数的调用" << endl;

	}


	//析构函数
	~Person()
	{
		cout << "Person 析构函数的调用" << endl;
	}
private:
	int m_age;
};

//调用
void test01()
{
	////1.括号法
	//Person p1; //默认构造函数的调用
	//Person p2(10);	//有参构造函数调用  
	//Person p3(p2);	//拷贝构造函数调用

	//2.显示法
	Person p1;
	Person p2 = Person(10);	//有参构造
	Person p3 = Person(p2);

	//3.隐式转换法
	Person p4 = 10; // 相当于 Person p4 = Person(10);
	Person p5 = p4;
}

int main()
{
	test01();
	return 0;
}

4.2.3 拷贝构造函数调用的时机

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

  • 使用一个已经创建完毕的对象来初始化一个对象
  • 值传递的方式给函数参数传值
  • 值方式返回局部对象

代码示例:

#include <iostream>

using namespace std;

//拷贝构造函数的使用时机






class Person
{
public:
	Person()
	{
		cout << "Person 默认构造函数调用" << endl;
	}
	Person(int age)	
	{
		m_Age = age; 
		cout << "Person 有参构造函数调用" << endl;

	}
	Person(const Person &p)
	{
		m_Age = p.m_Age;
		cout << "Person 拷贝构造函数调用" << endl;
	}

	~Person()
	{
		cout << "Person 析构函数调用" << endl;
	}

private:
	int m_Age;
};

//1. 使用一个已经创建完毕的对象来初始化一个新对象
void test01()
{
	Person p1(20);
	Person p2(p1);
}

//2. 值传递的方式给函数参数传值
void doWork(Person p)
{
	cout << (int)&p << endl;

}
void test02()
{
	Person p1;
	cout << (int)&p1 << endl;
	doWork(p1);
}

//3. 值方式返回局部对象

Person doWork2()
{
	Person p1;
	cout << (int) & p1 << endl;
	return p1;
}

void test03()
{
	Person p1 = doWork2();
	cout << (int)&p1 << endl;

}


int main()
{

	//test01();
	test02();
	
	//test03();

	return 0;
}

:第三点在VS2022(本人编译器)中好像经过优化了,他只显示一个默认构造函数的调用,出不来拷贝构造函数调用,要是有大佬能解决 dd我一下,我也学习一下。

4.2.4 构造函数的调用规则

1. C++中创建一个类,C++编译器会给每个类都添加至少3个函数。

  • 默认构造函数 (空实现)
  • 析构函数 (空实现)
  • 拷贝构造 (值拷贝)

下面代码中虽然没有拷贝构造函数依然可以拷贝:

#include <iostream>

using namespace std;



class Person
{
public:
	//构造函数
	Person()
	{
		cout << "构造函数调用" << endl;
	}
	//拷贝函数
	/*Person(const Person &p)
	{
		cout << "拷贝构造函数调用" << endl;
		m_Age = p.m_Age;
	}*/
	//析构函数
	~Person()
	{
		cout << "析构函数调用" << endl;
	}

	int m_Age;
};
//1. C++中创建一个类,编译器会自动提供三个函数
//	默认构造函数	(空实现)
//	析构函数		(空实现)
//	拷贝函数		(值拷贝)

void test01()
{
	Person p1;
	p1.m_Age = 18;
	Person p2(p1);
	cout << "p2的年龄是 " << p2.m_Age << endl;
}

int main()
{
	test01();


	return 0;
}

2. 如果我们写了有参构造函数,编译器就不再提供默认构造,但却依然提供拷贝构造。
如果我们写了拷贝构造函数,那么编译器就不再提供其他普通构造函数了。
在这里插入图片描述

4.2.5 深拷贝浅拷贝

编译器默认的拷贝函数是浅拷贝,浅拷贝会出现一个问题,比如下面的图中,当成员是一个指针的时候,浅拷贝只是把p1 p2的身高指向了一块内存空间而已,而因为hight 在堆上开辟的,对上开辟的需要程序员自己销毁,但两个p1 和 p2 两个析构函数销毁同一块空间,就会出现已经释放了 又需要再次释放,就是出现操作错误。
在这里插入图片描述

在这里插入图片描述

#include <iostream>

using namespace std;


//浅拷贝和深拷贝的区别

class Person
{
public:
	//构造函数
	Person()
	{
		cout << "默认构造函数调用" << endl;
	}
	//有参
	Person(int age, int hight)
	{
		m_Age = age;
		m_Hight = new int(hight);
	}


	Person(const Person& p)
	{
		m_Age = p.m_Age;
		//m_Hight = p.m_Hight 浅拷贝

		//深拷贝
		m_Hight = new int(*p.m_Hight);
		cout << "拷贝构造函数调用" << endl;

	}
	

	//析构函数
	~Person()
	{
		if (m_Hight != NULL)
		{
			delete(m_Hight);
		}

		cout << "析构函数调用" << endl;
	}


	int m_Age;
	int* m_Hight;
};

void test01()
{
	Person p1(18, 210);
	cout << "p1的年龄是 " << p1.m_Age << "p1的身高是 " << *(p1.m_Hight) << endl;
	Person p2(p1);
	cout << "p2的年龄是 " << p2.m_Age << "p2的身高是 " << *(p2.m_Hight) << endl;


}


int main()
{
	test01();

	return 0;
}

简单总结一下

  • 浅拷贝: 简单的赋值拷贝操作
  • 深拷贝: 在堆区中重新申请空间,进行拷贝操作。

4.2.6 初始化列表

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

类名(): 成员名(值), 成员名(值),..............
{

}
#include <iostream>


using namespace std;


//初始化列表
class Person
{
public:

	//传统的初始化
	/*Person(int a, int b, int c)
	{
		m_A = a, m_B = b, m_C = c;
	}*/

	//初始化列表
	/*Person() : m_A(10), m_B(20), m_C(30)
	{

	}*/

	Person(int a, int b, int c) : m_A(a), m_B(b), m_C(c)
	{

	}


	int m_A;
	int m_B;
	int m_C;
};

void test01()
{
	//Person p(10, 20, 30);
	//Person p;
	Person p(10, 20, 30);
	cout << "m_A = " << p.m_A << endl;
	cout << "m_B = " << p.m_B << endl;
	cout << "m_C = " << p.m_C << endl;

}


int main()
{
	test01();

	return 0;
}

4.2.7 类对象作类成员

C++中的成员可以是另一个类的对象,我们称该成员位对象成员。

class A{}
class B{
A a;
}
  • 当其他类作为本类成员时:
  • 构造时先构造其他类对象,再构造自身。
  • 析构时先析构自身,再析构其他类

在这里插入图片描述

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


class Phone
{
public:
	Phone(string name)
	{
		m_Pname = name;
		cout << "Phone 的构造函数调用" << endl;
	}

	~Phone()
	{
		cout << "Phone 的析构函数调用" << endl;
	}

	string m_Pname;
};

class Person
{
public:
	Person(string name, string pName) : m_Name(name), m_Phone(pName)
	{
		cout << "Person 的构造函数调用" << endl;
	}

	~Person()
	{
		cout << "Person 的析构函数调用" << endl;

	}

	string m_Name;
	Phone m_Phone;
};


//当其他类作为本类成员时,构造时先构造其他类对象,再构造自身。
//						 析构时先析构自身,再析构其他类
void test01()
{
	Person p("笑脸", "荣耀之魄");

	cout << p.m_Name << " " << p.m_Phone.m_Pname << endl;

}

int main()
{
	test01();
	return 0;
}

4.2.8 静态成员

静态成员变量

  • 所有对象共享同一份数据
  • 在编译阶段分配内存
  • 类内声明,类外初始化

注意:静态成员变量有两种访问方式 1.通过对象进行访问 2.通过类名进行访问

#include <iostream>

using namespace std;


//静态成员变量
//所有对象共享同一份数据
//在编译阶段分配内存
//类内声明,类外初始化

class Person
{
public:
	static int m_A;

	
	//静态成员变量也是有访问权限的 外界不让访问
private:
	static int m_B;
};
int Person:: m_A = 100;


void test01()
{
	Person p1;
	cout << p1.m_A << endl;
	Person p2;
	p2.m_A = 200;
	cout << p2.m_A << endl;

}

//静态成员不属于某个对象上,所有对象都共享一份数据
//因此静态成员变量有两种访问方式
void test02()
{
	//1. 通过对象进行访问
	Person p1;
	cout << p1.m_A << endl;

	//2. 通过类名进行访问
	cout << Person::m_A << endl;
}
 
int main()
{
	//test01();
	test02();
	return 0;
}

静态成员函数

  • 所有对象共享同一个函数
  • 静态成员函数只能访问静态成员变量

注意:静态成员函数有两种访问方式 1.通过对象进行访问 2.通过类名进行访问

#include <iostream>

using namespace std;

//静态成员函数
//所有对象共享同一个函数
//静态成员函数只能访问静态成员变量
class Person
{
public:

	static void fun()
	{
		cout << "fun1的调用" << endl;
		m_A = 100;
		//m_B = 200;	ERROR   ---  //静态成员函数只能访问静态成员变量
	}


	static int m_A;
	int m_B;

	//也是有访问权限的
private:
	static void fun2()
	{
		cout << "fun2的调用" << endl;
		m_A = 1100;
	}
};

int Person::m_A = 10;


void test01()
{
	Person p;
	p.fun();
	cout << p.m_A << endl;

	//p.fun2()访问不了

}


int main()
{
	test01();


	return 0;
}

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

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

在C++中,类内的成员变量和成员函数分开存储。

#include <iostream>

using namespace std;

//成员变量和成员函数是分开存储的


class Person
{
	int m_A;	//非静态成员变量 属于类的对象上
	static int m_B;		//静态成员变量 不属于类的对象上	不占类中内存

	void fun()		//非静态成员函数	不占类中内存
	{

	}
	static void fun2() //静态的成员函数 不占类中内存
	{

	}


};

//类内声明 类外初始化
int Person::m_B = 0;
void test01()
{
	Person p;
	//空对象占用内存空间为1
	cout << "p 占用内存空间为 " << sizeof(p) << endl;
}

void test02()
{
	Person p;

	cout << "p 占用内存空间为 " << sizeof(p) << endl;

}

int main()
{
	//test01();
	test02();

	return 0;
}

4.3.2 this指针

  • this指针指向被调用的成员函数所属的对象
  • this指针是隐含每一个非静态成员函数内的一个指针。
  • this指针不需要定义,直接使用即可

this指针的用途:

  • 当形参和成员变量同名时,可以用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可以使用*return this
#include <iostream>

using namespace std;

class Person
{
public:
	Person(int age)
	{
		this->age = age;
	}

	Person& PersonAddAge(const Person& p)
	{
		this->age += p.age;
		return *this;		// 现在返回类型是Person& 就是返回的p2 本身 可以一直叠加的修改
							// 如果返回类型是Person 就是一直返回p2' p2'' p2''' p2的复制版
	}

	//Person* PersonAddAge(const Person& p)
	//{
	//	this->age += p.age;
	//	return this;
	//}

	int age;
};

//1.解决名称冲突
void test01()
{
	Person p1(10);

	cout << "p1的年龄 " << p1.age << endl;

}

//2. 返回对象本身用*this
void test02()
{
	Person p1(10);
	Person p2(10);

	//链式编程
	p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
	//p2.PersonAddAge(p1)->PersonAddAge(p1)->PersonAddAge(p1);

	cout << "p2的年龄 " << p2.age << endl;

}


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

4.3.3 空指针访问成员函数

C++中空指针也是可以调用成员函数的,但是也要注意函数体内部有没有用到this指针

#include <iostream>

using namespace std;


class Person
{
public:

	void fun1()
	{
		cout << "fun1 函数调用" << endl;
	}

	void fun2()
	{
		if (this == NULL)
			return;

		// 属性在调用的时候默认前面有一个this,即this->mAge
		// 所以当对象p1为NULL时候 this 也是NULL 对其进行操作就会报错。
		cout << "fun2 函数调用 年龄:" << m_Age << endl; 
	}



	int m_Age;
};


void test01()
{
	Person* p1 = NULL;
	p1->fun1();
	p1->fun2();
}


int main()
{
	test01();
	return 0;
}

4.3.4 const 修饰成员函数

常函数:

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

常对象

  • 声明对象前 加const 称该对象是 常对象
  • 常对象只能调用常函数
#include <iostream>

using namespace std;


//常函数
class Person
{
public:

	//1. 常函数
	void fun1() const
	{
		//this->m_A = 10;	//	const 修饰后 连值也不可以修改
		//this = NULL	//this指针 不可以修改指针的指向	
		this->m_B = 10;	//若想特例修改需要使用mutable来修饰
	}
	void fun2()
	{

	}

	int m_A;
	mutable int m_B;	//若想特例修改需要使用mutable来修饰
};

//2. 常对象
void test01()
{
	const Person p1;
	//p1.m_A = 10;	//不可以修改
	p1.m_B = 10;	//mutable来修饰的依然可以修改

	//常对象只能调用常函数
	p1.fun1();
	//p1.fun2();	//不能调用

}



int main()
{
	test01();

	return 0;
}

4.4 友元

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

4.4.1全局函数作友元

#include <iostream>
#include <string>

using namespace std;

class Building
{
	//goodF全局函数是 Building类的好朋友 所以可以访问Building的私有成员
	friend void goodF(Building& b);

public:
	Building()
	{
		m_SittingRoom = "客厅";
		m_BedRoom = "卧室";
	}
public:
	string m_SittingRoom;	//客厅

private:
	string m_BedRoom;	//卧室
};

//全局函数
void goodF(Building &b)
{
	cout << "好朋友正在访问 " << b.m_SittingRoom << endl;
	cout << "好朋友正在访问 " << b.m_BedRoom << endl;

}


void test01()
{
	Building b;
	goodF(b);
}

int main()
{
	test01();

	return 0;
}

4.4.2 类作友元

#include <iostream>
#include <string>

using namespace std;

//类作友元

//建筑物类
class Building
{
	friend class GoodGay;	//##########类作好朋友!! 类作友元
public:
	Building();	//构造函数


//成员变量
public:
	string m_SittingRoom;

private:
	string m_BedRoom;
};


//好基友类
class GoodGay
{

public:
	GoodGay();	//构造函数

	void visit();	//参观函数访问Building中的属性(公共和私用)



//成员变量
public:
	Building* building;

};



// --------------------------------------------------------------------------------
//类外去写成员函数
Building::Building()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";

}
GoodGay::GoodGay()
{
	//创建一个建筑物的对象
	building = new Building;
}


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

}
// ---------------------------------------------------------------------------------


void test01()
{
	GoodGay g;
	g.visit();

}


int main()
{
	test01();

	return 0;
}

4.4.3 成员函数作友元

#include <iostream>

using namespace std;

//建筑物类
class Building;

//好基友类
class GoodGay
{
public:
	GoodGay();

	void visit();	//可以访问公共和私有
	void visit01();	//可以访问公共

public:
	Building* building;
};

//建筑物类
class Building
{
	friend void GoodGay::visit();	//成员函数作友元

public:
	Building();


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

//------------------------------
Building::Building()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";

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

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

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

}
//------------------------------


void test01()
{
	GoodGay g;
	g.visit();
	g.visit01();
}


int main()
{
	test01();
	return 0;
}

在这里插入图片描述

4.5 运算符重载

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

  • 内置的数据类型表达式的运算符是不可能改变的。
  • 不要滥用运算符重载

4.5.1 加号运算符重载

作用:可以使自定义类型内的成员进行相加

  • 可以利用成员函数重载
  • 也可以利用全局函数重载
#include <iostream>

using namespace std;

class Person
{
public:

	//1. 成员函数重载加号
	//Person operator+(Person& p)
	//{
	//	Person t;
	//	t.m_A = this->m_A + p.m_A;
	//	t.m_B = this->m_B + p.m_B;
	//	
	//	return t;
	//}


	int m_A;
	int m_B;
};

// 2. 全局函数来重载加号运算符
Person operator+(Person& p1, Person& p2)
{
	Person t;
	t.m_A = p1.m_A + p2.m_A;
	t.m_B = p1.m_B +p2.m_B;

	return t;
}

Person operator+(Person& p, int x)
{
	Person t;
	t.m_A = p.m_A + x;
	t.m_B = p.m_B + x;

	return t;
}


void test01()
{
	Person p1;
	p1.m_A = 10;
	p1.m_B = 10;
	Person p2;
	p2.m_A = 10;
	p2.m_B = 10;

	//Person p3 = p1.operator+(p2);	//成员函数重载的的本质调用
	//Person p3 = operator+(p1, p2);	//全局函数重载的的本质调用
	Person p3 = p1 + p2;			//简化版本

	cout << "p3.m_A = " << p3.m_A << endl;
	cout << "p3.m_B = " << p3.m_B << endl;

	//运算符重载 也可以发生函数重载
	Person p4 = p1 + 100;
	cout << "p4.m_A = " << p4.m_A << endl;
	cout << "p4.m_B = " << p4.m_B << endl;


}



int main()
{
	test01();
	return 0;
}

4.5.2 左移运算符重载

作用 :可以输出自定义数据类型
只有全局函数重载才可以是cout在左边
用成员函数重载的话cout就会变到右边 不推荐

#include <iostream>

using namespace std;

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

private:
	int m_A;
	int m_B;
};



ostream& operator<< (ostream& cout, Person &p)
{
	cout << "m_A = " << p.m_A << " m_B = " << p.m_B;
	return cout;
}


void test01()
{
	Person p(10, 10);
	//operator<< (cout, p);	//本质
	cout << p << " hello world" << endl;
}


int main()
{
	test01();
	return 0;
}

4.5.3 递增运算符重载

作用:通过重载运算符,实现自己的整形数据.

#include <iostream>

using namespace std;

class MyInteger
{
	friend ostream& operator<< (ostream& cout, MyInteger myInt);
public:
	MyInteger()
	{
		m_num = 0;
	}

	//重载前置++ 返回引用是为了一直对一个数据进行递增操作
	//该函数返回参数是引用类型的, 因为前置++需要返回其本体,不可以返回副本  ++(++a)支持这种操作
	MyInteger& operator++()
	{
		m_num++;

		return *this;
	}

	//重载后置++
	//该函数返回参数是引用类型的, 因为后置--需要返回其副本,不可以返回本体 (a++)++不支持这种操作
	MyInteger operator++(int)	//int 代表占位参数 可以用于区分前置和后置递增
	{
		MyInteger t = *this;
		m_num++;
		return t;
	}

private:
	int m_num;
};


//重载 << 运算符
ostream& operator<< (ostream& cout, MyInteger myInt)
{
	cout << myInt.m_num;
	return cout;
}

void test01()
{
	MyInteger myInt;

	cout << myInt << endl;
	cout << ++(++myInt) << endl;
	cout << myInt << endl;


}

void test02()
{
	MyInteger myInt;
	cout << myInt << endl;		//0
	cout << myInt++ << endl;	// 0
	cout << myInt << endl;	//1
}

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

注意:

  • 在这里重载的<<操作符和上一节不一样,因为我的后置加加是创建临时副本的,所以不能用引用的方式传递。

4.5.4 赋值运算符重载

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

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

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

#include <iostream>

using namespace std;


class Person
{
public:
	Person(int age)
	{
		m_Age = new int(age);
	}


	~Person()
	{
		if (m_Age != NULL)
		{
			delete m_Age;
		}
	}

	Person& operator= (Person& p)
	{
		//编译器提供的是浅拷贝
		//m_Age = p.m_Age;

		//应该先判断是否有属性在堆区,如果有先释放干净,然后再拷贝
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}

		m_Age = new int(*p.m_Age);

		return *this;
	}


	int* m_Age;
};

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

	p1 = p2 = p3;

	

	cout << "p1的年龄是 " << *p1.m_Age << endl;
	cout << "p2的年龄是 " << *p2.m_Age << endl;
	cout << "p3的年龄是 " << *p3.m_Age << endl;


}


int main()
{
	test01();
	
	/*int a = 10;
	int b = 20;
	int c = 30;
	a = b = c;


	cout << a << endl;
	cout << b << endl;
	cout << c << endl;*/

	
	return 0;
}

有点像上面拷贝函数中的深拷贝和浅拷贝。

4.5.5 关系运算符重载

#include <iostream>
#include <string>

using namespace std;

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

	bool operator==(Person& p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
			return true;
		else
			return false;
	}

	bool operator!=(Person& p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
			return false;
		else
			return true;
	}


	string m_Name;
	int m_Age;
};


void test01()
{
	Person p1("kxq", 21);
	Person p2("kxq", 21);

	/*if (p1 == p2)
		cout << "p1 和 p2 是相等的!" << endl;
	else
		cout << "p1 和 p2 是不相等的!" << endl;*/

	if(p1 != p2)
		cout << "p1 和 p2 是不相等的!" << endl;
	else
		cout << "p1 和 p2 是相等的!" << endl;

}


int main()
{
	test01();
	return 0;
}

4.5.6 函数调用运算符重载

  • 函数调用运算符()也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此被称为仿函数
  • 仿函数没有固写法,非常灵活
#include <iostream>
#include <string>
using namespace std;

class MyPrint
{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}
};

void MyPrint02(string text)
{
	cout << text << endl;
}


void test01()
{
	MyPrint myFunc;
	myFunc("hello world");//类似于函数调用 又称仿函数
	MyPrint02("dsadsadasdas");
}

//仿函数非常灵活 没有固定的写法
//加法类

class MyAdd
{
public:
	int operator()(int a, int b)
	{
		return a + b;
	}
};


void test02()
{
	MyAdd myadd;
	int ret = myadd(10, 20);
	cout << ret << endl;


	//匿名函数对象
	cout << MyAdd()(100, 200) << endl;

}


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

4.6 继承

继承是面向对象的三大特性之一

4.6.1 继承的基本语法

  • 继承的好处:减少重复的代码
  • 语法 class 子类 : 继承方式 父类
  • 子类 也称 派生类
  • 父类 也称 基类
#include <iostream>

using namespace std;

//继承
class BasePage
{
public:
	void header()
	{
		cout << "首页、公开课、登录、注册...(公共头部)" << endl;
	}
	void footer()
	{
		cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
	}
	void left()
	{
		
		cout << "Java、Python、C++ ... (公共分类列表)" << endl;
	}
};
//继承的好处:减少重复的代码 
//语法  class 子类 : 继承方式 父类
//子类  也称 派生类
//父类  也称 基类
class Java : public BasePage
{
public:
	void content()
	{
		cout << "Java学科视频" << endl;
	}
};

class Python : public BasePage
{
public:
	void content()
	{
		cout << "Python学科视频" << endl;
	}
};
class Cpp : public BasePage
{
public:
	void content()
	{
		cout << "Cpp学科视频" << endl;
	}
};

void test01()
{
	cout << "Java下载视频页面如下: " << endl;
	Java ja;
	ja.header();
	ja.footer();
	ja.left();
	ja.content();


	cout << " ------------------------------- " << endl;
	cout << "Python下载视频页面如下: " << endl;
	Python py;
	py.header();
	py.footer();
	py.left();
	py.content();


	cout << " ------------------------------- " << endl;
	cout << "C++下载视频页面如下: " << endl;
	Cpp cpp;
	cpp.header();
	cpp.footer();
	cpp.left();
	cpp.content();

}




int main()
{
	test01();

	return 0;
}

4.6.2 继承的方式

继承的方式分为三种: 公共继承,保护继承,私有继承。

  • 父类中的私有成员,无论以什么方式继承,子类都无法访问
  • 父类中的公共保护成员,以公共的方式继承到子类,依然还是公共和保护的权限。
  • 父类中的公共保护成员,以保护的方式继承到子类,全部变为保护权限。
  • 父类中的公共保护成员,以私有的方式继承到子类,全部变为私有权限。
#include <iostream>

using namespace std;

class Base1
{
public:
	int m_A;
protected:
	int m_B;
private:
	int m_C;
};
//公共继承
class Son1:public Base1
{
public:
	void fun()
	{
		m_A = 100;		//还是公共
		m_B = 100;		//还是保护
		//m_C = 100;	//父类中的私有权限,无论如何继承 过来还是私有的
	}
};
void test01()
{

	Son1 s1;
	s1.m_A = 10;	//公共权限可以
	//s1.m_B = 20;	//保护权限类外不可以访问
}
//保护继承
class Son2 : protected Base1
{
	void fun()
	{
		m_A = 10;	//保护权限类内可以访问
		m_B = 10;	//保护权限类内可以访问
		//m_C = 10;	//父类中的私有权限,无论如何继承 过来还是私有的
	}
};
void test02()
{
	Son2 s2;
	//s2.m_A = 100;	//保护权限类外不可以访问
	//s2.m_B = 100;	//保护权限类外不可以访问
}
class Son3 : private Base1
{
	void fun()
	{
		m_A = 10;	//变为私有
		m_B = 10;	//变为私有
		//m_C = 10;
	}
};
class GrandSon3 : public Son3
{
	void fun()
	{
		//m_A = 10;	//即使接下来用公共继承也无法访问,因为在Son3的类中已经变成私有了
		//m_B = 10;	//即使接下来用公共继承也无法访问,因为在Son3的类中已经变成私有了
		//m_C = 10;
	}
};
void test03()
{
	Son3 s3;
	//s3.m_A;	//无法访问
	//s3.m_B; //无法访问
}

int main()
{

	return 0;
}

4.6.3 继承中的对象模型

  • 父类中所有非静态成员都会被子类继承下去
  • 父类中私有成员属性 是被编译器给隐藏了,因此是访问不到的,但确实被继承下去了。
#include <iostream>

using namespace std;


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

class Son : public Base
{
public:
	int m_D;
};


void test01()
{
	Son s1;
	//16
	//父类中所有非静态成员都会被子类继承下去。
	//父类中私有成员属性 是被编译器给隐藏了,因此是访问不到的,但确实被继承下去了。
	cout << "s1在内存的大小 " << sizeof(s1) << endl;

}


int main()
{
	test01();
	return 0;
}

4.6.4 继承中的构造和析构顺序

  • 继承中先调用父类构造函数,再调用子类构造函数,析构的顺序与构造的顺序相反。

在这里插入图片描述

#include <iostream>

using namespace std;

class Base
{
public:
	Base()
	{
		cout << "Base构造函数调用!" << endl;
	}
	~Base()
	{
		cout << "Base析构函数调用!" << endl;
	}
};

class Son : public Base
{
public:
	Son()
	{
		cout << "Son构造函数调用!" << endl;
	}
	~Son()
	{
		cout << "Son析构函数调用!" << endl;
	}
};

void test01()
{
	Son s;
}


int main()
{
	test01();
	return 0;
}

4.6.5 继承同名成员处理方式

  • 子类对象可以直接访问到子类中同名成员
  • 子类对象加作用域可以访问到父类同名成员
  • 当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类中同名函数。
#include <iostream>

using namespace std;


//
class Base
{
public:
	Base()
	{
		m_A = 200;
	}

	void fun()
	{
		cout << "Base - fun函数的调用 " << endl;
	}

	void fun(int a)
	{
		cout << "Base - fun(int)函数的调用 " << endl;
	}

	int m_A;
};

class Son : public Base
{
public:
	Son()
	{
		m_A = 100;
	}

	void fun()
	{
		cout << "Son - fun函数的调用 " << endl;
	}

	int m_A;
};

void test01()
{
	Son s1;
	cout << "Son 中的 m_A = " << s1.m_A << endl;
	//如果子类对象 访问到父类中同名成员,需要加作用域
	cout << "Base 中的 m_A = " << s1.Base::m_A << endl;

}


void testo2()
{
	Son s1;
	s1.fun();
	s1.Base::fun();

	//如果子类中出现了父类同名的成员函数,子类同名成员会隐藏掉父类中所有同名成员函数
	//如果想访问到父类中被隐藏的同名成员函数,需要加作用域。
	//s1.fun(100);
	s1.Base::fun(100);


}
int main()
{
	//test01();
	testo2();
	return 0;
}

4.6.6 继承中同名静态成员处理方式

静态成员和上一节同名基本一致,只不过访问的时候多了一种类名访问

  • 以对象访问(静态和非静态)
  • 以类名访问(静态)
#include <iostream>

using namespace std;


class Base
{
public:
	static void fun()
	{
		cout << "Base - static fun()调用 " << endl;
	}

	static void fun(int a)
	{
		cout << "Base - static fun(int)调用 " << endl;
	}

	static int m_A;	//类内声明 类外初始化
};
int Base::m_A = 100;
class Son: public Base
{
public:
	static void fun()
	{
		cout << "Son - static fun()调用 " << endl;
	}

	static int m_A;
};
int Son::m_A = 200;


void test01()
{
	//1. 通过对象访问
	Son s1;
	cout << " Son 中的 m_A = " << s1.m_A << endl;
	cout << " Base 中的 m_A = " << s1.Base::m_A << endl;
	//2. 通过类名访问
	cout << "Son 中的 m_A = " << Son::m_A << endl;
	cout << "Base 中的 m_A = " << Base::m_A << endl;
	//第一个:: 代表类名方式访问 第二个:: 代表访问父类作用域下
	cout << "Base 中的 m_A = " << Son::Base::m_A << endl;
}
void test02()
{
	//1.通过对象访问
	cout << "通过对象访问" << endl;

	Son s1;
	s1.fun();
	s1.Base::fun();

	//2.通过类名访问
	cout << "通过类名访问" << endl;
	Son::fun();
	Base::fun();
	Son::Base::fun();
	Son::Base::fun(10);

}

int main()
{
	//test01();
	
	test02();

	return 0;
}

4.6.7 多继承语法

C++中支持多继承的语法, class 子类 : 继承方式 父类,继承方式 父类,......
但是在开发过程中不建议使用,因为如果两个父类中出现了同名情况,子类访问时,需要加作用域。

#include <iostream>

using namespace std;

class Base1
{
public:
	Base1()
	{
		m_A = 100;
	}

	int m_A;
};

class Base2
{
public:
	Base2()
	{
		m_A = 200;
	}

	int m_A = 200;
};

class Son :public Base1, public Base2
{
public:

	int m_C;
	int m_D;
};


void test01()
{
	Son s1;
	cout << sizeof(s1) << endl;
	
	cout << "Base1 m_A = " << s1.Base1::m_A << endl;
	cout << "Base2 m_A = " << s1.Base2::m_A << endl;

}


int main()
{

	test01();
	return 0;
}

在这里插入图片描述

4.6.8 菱形继承

菱形继承的概念:

  • 两个派生类继承同一个基类
  • 又有某个类同时继承了两个派生类
  • 这种继承被称为菱形继承,或者钻石继承

典型案例:《。。。》
在这里插入图片描述
菱形继承的问题:

  • 羊继承了动物的数据,驼也继承了动物的数据,当羊驼使用数据的时候,就会产生二义性。
  • 羊驼同样还继承了两份动物的数据,造成了资源浪费

解决菱形继承问题 — 虚继承

  • 虚继承其实是产生了一个虚基类指针,这个指针指向虚基类表。
  • 这个表中纪录了一个偏移量,指向相同的一个数据m_Age;
  • 父类变成虚基类后,共享一个内存,上面 的操作变成了 修改操作。
#include <iostream>

using namespace std;


//动物类
class Animal 
{
public:

	int m_Age;
};

//利用虚继承来解决菱形继承的问题 virtual
//在继承之前加上关键字 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 = 18;


	st.Tuo::m_Age = 28;
	//将18修改成了28
	//虚继承其实是产生了一个虚基类指针,这个指针指向虚基类表,这个表中纪录了一个偏移量,
	//指向相同的一个数据m_Age; 所以说父类变成虚基类后,共享一个内存,上面 的操作变成了 修改操作。
	


	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();
	return 0;
}

4.7 多态

多态是C++面向对象三大特性之一, 一个接口有多种形态。

4.7.1 多态的基本概念

多态分为两类:

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

静态多态和动态多态区别

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

using namespace std;


class Animal
{
public:
	//虚函数 
	virtual void speak()
	{
		cout << "动物在说话" << endl;
	}
};

class Cat:public Animal
{
public:
	void speak()
	{
		cout << "小猫在说话" << endl;
	}
};

class Dog : public Animal
{
public:
	void speak()
	{
		cout << "小狗在说话" << endl;
	}
};




//执行说话函数
//输出动物在说话 地址早绑定 在编译阶段就确定了函数的地址
//想要输出猫说话 那么函数的地址就不能提前绑定,需要在运行阶段进行绑定 地址晚绑定。 

//动态多态满足条件
//1. 有继承关系
//2. 子类要重写父类的虚函数

//动态多态的使用
//父类的指针或者引用 指向子类对象


void doSpeak(Animal &animal)	//父类引用接受子类对象
{
	animal.speak();
}

void test01()
{
	Cat cat;
	doSpeak(cat);
	Dog dog;
	doSpeak(dog);
}



int main()
{
	test01();
	return 0;
}

总结:
多态满足条件:

  • 有继承关系
  • 子类要重写父类的虚函数

动态多态的使用

  • 父类的指针或者引用 指向子类对象

重写与重载不一样。
重写: 函数返回值类型 函数名 参数列表完全一致称为重写

多态的原理
当未给父类加入virtual时 类的大小为1 即为空类.
在这里插入图片描述

当加入virtual后大小变为4,其内部变成了一个vfptr的指针指向了一个vftable的表,表中有&Animal::speak
在这里插入图片描述
而子类Cat 当没有重写speak函数时候会调用Animal::speak
在这里插入图片描述

而重写后vfpter指向的vftable中是自己函数的地址&Cat::speak

在这里插入图片描述

4.7.2 多态案例一-计算机类

案例描述:
分别利用普通写法和多态技术,设计实现操作数进行运算的计算器类
多态的优点:

  • 代码组织结构清晰
  • 可读性强
  • 利用前期和后期的扩展以及维护

在这里插入图片描述

下面是我对于这个案例的理解
真正的开发中的代码肯定不止这么一点,先将上面代码想象成一个游戏开发的代码.
第一点:
如果我们需要更新游戏或者新增游戏内容,我们如果直接在源码上修改的话,那源码中所有的功能都得暂时终止对吗,也不方便观看,而多态就不需要,它可以直接在下面新增代码,写好之后测试一下就好了。
第二点:
如果新增的功能有bug出现,我们会知道,bug肯定在新增的功能中,所以去新增的子类中查找就好了。相反你要是在源码中寻找bug,小心越找越多哦。

总结四个字: 开闭原则 对扩展进行开放,对修改及进行关闭

#include <iostream>

using namespace std;

//普通写法:
class Calculator
{
public:
	int getResult(string op)
	{
		if (op == "+")
		{
			return m_Num1 + m_Num2;
		}
		else if (op == "-")
		{
			return m_Num1 - m_Num2;
		}
		else if (op == "*")
		{
			return m_Num1 * m_Num2;
		}
		//如果想拓展新功能,需要修改源码
		//在真是开发中 体长 开闭原则
		//开闭原则: 对扩展进行开放,对修改及进行关闭
	}

	int m_Num1;
	int m_Num2;
};

void test01()
{
	Calculator c;
	c.m_Num1 = 10;
	c.m_Num2 = 20;

	cout << c.m_Num1 << " + " << c.m_Num2 << " =  " << c.getResult("+") << endl;
	cout << c.m_Num1 << " - " << c.m_Num2 << " =  " << c.getResult("-") << endl;
	cout << c.m_Num1 << " * " << c.m_Num2 << " =  " << c.getResult("*") << endl;


}

//多态写法
//好处
//1. 组织结构清晰
//2. 可读性高
//3. 对于前期和后期的维护性高
class AbstractCalculator
{
public:
	virtual int getResult()
	{
		return 0;
	}

	int m_Num1;
	int m_Num2;
};

//加法类
class AddCalculator:public AbstractCalculator
{
public:
	int getResult()
	{
		return m_Num1 + m_Num2;
	}
};

//减法类
class SubCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_Num1 - m_Num2;
	}
};
//乘法类
class MulCalculator :public AbstractCalculator
{
public:
	int getResult()
	{
		return m_Num1 * m_Num2;
	}
};

void test02()
{
	//父类的指针或者引用   指向	 子类对象
	AbstractCalculator* abs = new AddCalculator;
	abs->m_Num1 = 10;
	abs->m_Num2 = 20;
	cout << abs->m_Num1 << " + " << abs->m_Num2 << " = " << abs->getResult() << endl;
	delete abs;

	abs = new SubCalculator;
	abs->m_Num1 = 10;
	abs->m_Num2 = 20;
	cout << abs->m_Num1 << " - " << abs->m_Num2 << " = " << abs->getResult() << endl;
	delete abs;


	abs = new MulCalculator;
	abs->m_Num1 = 10;
	abs->m_Num2 = 20;
	cout << abs->m_Num1 << " * " << abs->m_Num2 << " = " << abs->getResult() << endl;
	delete abs;

}


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

4.7.3 纯虚函数和抽象类

通过上节中可以发现,在多态中,通常父类中的虚函数的实现毫无意义,主要是调用子类重写的内容。
因此可以将虚函数改为纯虚函数
纯虚函数语法:virtual 返回值类型 函数名 (参数列表) = 0;
当类中有了纯虚函数,这个类也成为抽象类。

抽象类特点:

  • 无法实例化对象。
  • 子类必须重写抽象类中的纯虚函数,否则也属于抽象类。
#include <iostream>

using namespace std;


class Base
{
public:
	virtual void fun() = 0;
};


class Son :public Base
{
public:
	virtual void fun()
	{
		cout << "fun函数的调用 " << endl;
	}
};


void test01()
{
	//1.抽象类无法示例化对象
	//Base b;	//error
	//new Base;	//	error

	//2.子类必须重写父类中的纯虚函数,否则无法实例化对象 也属于抽象类。
	//Son s;	//


	Base* b = new Son;

	b->fun();
}


int main()
{
	test01();
	return 0;
}

4.7.4 多态案例二-制作饮品

在这里插入图片描述

#include <iostream>

using namespace std;


class AbstractDrinking
{
public:
	//煮水
	virtual void Boil() = 0;
	
	//冲泡
	virtual void Brew() = 0;

	//倒入杯中
	virtual void PourInCup() = 0;

	//加入辅料
	virtual void PutSomething() = 0;


	//制作饮品
	void makeDrink()
	{
		Boil();
		Brew();
		PourInCup();
		PutSomething();
	}

};

class Coffee :public AbstractDrinking
{
public:
	//煮水
	virtual void Boil()
	{
		cout << "煮入农夫山泉" << endl;
	}

	//冲泡
	virtual void Brew()
	{
		cout << "泡入咖啡" << endl;
	}

	//倒入杯中
	virtual void PourInCup()
	{
		cout << "倒入咖啡杯中" << endl;
	}

	//加入辅料
	virtual void PutSomething()
	{
		cout << "加入糖和牛奶" << endl;
	}
};

//制作茶叶
class Tea :public AbstractDrinking
{
public:
	//煮水
	virtual void Boil()
	{
		cout << "煮入怡宝" << endl;
	}

	//冲泡
	virtual void Brew()
	{
		cout << "冲泡茶叶" << endl;
	}

	//倒入杯中
	virtual void PourInCup()
	{
		cout << "倒入超级无敌巨大杯中" << endl;
	}

	//加入辅料
	virtual void PutSomething()
	{
		cout << "加入超级无敌巨大枸杞" << endl;
	}
};

void doWork(AbstractDrinking* abs)
{
	abs->makeDrink();
	delete abs;
}


void Test01()
{
	//制作咖啡
	doWork(new Coffee);

	cout << "---------------------------" << endl;
	//制作茶
	doWork(new Tea);
}


int main()
{
	Test01();
	return 0;
}

4.7.5 虚析构和纯虚析构

多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时,无法调用子类的析构函数
解决方案:

  • 将父类中的析构函数改为虚析构或者纯虚析构
#include <iostream>
#include <string>
using namespace std;


class Animal
{
public:
	Animal()
	{
		cout << "Aminal 的构造函数调用 " << endl;
	}

	//纯虚函数
	virtual void sepak() = 0;

	//父类指针在析构的时候 不会调用子类的析构函数,导致子类如果有堆区属性,会出现内存泄露
	//虚析构可以解决此问题
	/*virtual ~Animal()
	{
		cout << "Aminal 的析构函数调用 " << endl;
	}*/

	//纯虚析构
	virtual ~Animal() = 0;
};


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


class Cat : public Animal
{
public:
	Cat(string name)
	{
		cout << "Cat 的构造函数调用 " << endl;

		m_Name = new string(name);
	}


	void sepak()
	{
		cout << *m_Name << "小猫在说话" << endl;
	}

	~Cat()
	{
		if (m_Name != NULL)
		{
			cout << "Cat 的析构函数调用 " << endl;
			delete(m_Name);
			m_Name = NULL;
		}

	}

	string* m_Name;
};


void test01()
{
	Animal* a = new Cat("Tom");
	a->sepak();

	//父类指针在析构的时候 不会调用子类的析构函数,导致子类如果有堆区属性,会出现内存泄露
	delete a;
}


int main()
{
	test01();

	return 0;
}
  • 虚析构和纯虚析构就是用来解决父类指针无法释放子类对象
  • 如果子类没有数据开辟到堆区,可以不用写虚析构和纯虚析构
  • 拥有纯虚析构函数的类也属于抽象类
  • 纯虚析构 需要类内声明,类外实现

4.7.6 多态案例三-电脑组装

在这里插入图片描述

#include <iostream>

using namespace std;


//抽象不同零件类
//抽象cpu类
class Cpu
{
public:
	virtual void calculate() = 0;
};

//抽象显卡类
class VideoCard
{
public:
	virtual void display() = 0;
};

//抽象内存类
class Memory
{
public:
	virtual void storage() = 0;
};

//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------


//电脑类
class Computer
{
public:
	Computer(Cpu* cpu, VideoCard* vc, Memory* mem)
	{
		m_cpu = cpu;
		m_vc = vc;
		m_mem = mem;
	}

	//工作。
	void work()
	{
		m_cpu->calculate();
		m_vc->display();
		m_mem->storage();
	}
	virtual ~Computer()
	{
		if (m_cpu != NULL)
		{
			delete m_cpu;
			m_cpu = NULL;
		}

		if (m_vc != NULL)
		{
			delete m_vc;
			m_vc = NULL;
		}

		if (m_mem != NULL)
		{
			delete m_mem;
			m_mem = NULL;
		}
	}
private:
	Cpu* m_cpu;
	VideoCard* m_vc;
	Memory* m_mem;
};

//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------

//具体的厂商
//Intel厂商
class IntelCpu:public Cpu
{
	virtual void calculate()
	{
		cout << "Intel的cpu开始计算了!" << endl;
	}
};

class IntelVideoCard :public VideoCard
{
	virtual void display()
	{
		cout << "Intel的显卡开始显示了!" << endl;
	}
};

class IntelMemory :public Memory
{
	virtual void storage()
	{
		cout << "Intel的内存条开始存储了!" << endl;
	}
};


//Lenovo厂商
class LenovoCpu :public Cpu
{
	virtual void calculate()
	{
		cout << "Lenovo的cpu开始计算了!" << endl;
	}
};

class LenovoVideoCard :public VideoCard
{
	virtual void display()
	{
		cout << "Lenovo的显卡开始显示了!" << endl;
	}
};

class LenovolMemory :public Memory
{
	virtual void storage()
	{
		cout << "Lenovo的内存条开始存储了!" << endl;
	}
};

//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------

void test01()
{
	//第一台电脑零件
	Cpu* interCpu = new IntelCpu;
	VideoCard* intelCard = new IntelVideoCard;
	Memory* intelMemory = new IntelMemory;

	//创建第一台电脑
	cout << "第一台电脑创建完成:" << endl;
	Computer* computer = new Computer(interCpu, intelCard, intelMemory);
	computer->work();
	delete computer;

	cout << "-------------------------------------" << endl;
	cout << "第二台电脑创建完成:" << endl;
	computer = new Computer(new LenovoCpu, new LenovoVideoCard, new LenovolMemory);
	computer->work();


	cout << "-------------------------------------" << endl;
	cout << "第三台电脑创建完成:" << endl;
	computer = new Computer(new LenovoCpu, new IntelVideoCard, new LenovolMemory);
	computer->work();

}


int main()
{
	test01();
	return 0;
}

5. 文件操作

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

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

操作文件的三大类:
3. ofstream 写操作
4. ifstream 读操作
5. fstream 读写操作

5.1 文本文件

5.1.1 写文件

写文件的流程

  • 包含头文件
  • 创建流对象 ofstream ofs;
  • 打开文件 - ofs.open("路径",打开方式);
  • 写数据
  • 关闭文件

在这里插入图片描述

#include <iostream>
#include <fstream>


using namespace std;


void test01()
{
	//1. 包含头文件 <fstream>

	//2. 创建流
	ofstream ofs;

	//3. 指定打开方式
	ofs.open("test.txt", ios::out);

	//4. 写内容d  
	ofs << "姓名: kxq" << endl;
	ofs << "性别: 男" << endl;
	ofs << "年龄: 18" << endl;

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


}

int main()
{
	test01();
	return 0;
}

在这里插入图片描述

5.1.2 读文件

读文件的流程:

  • 包含头文件
  • 创建流对象 - ifstream ifs;
  • 打开文件并判断是否打开成功 - ifs.open("文件路径", 打开方式);
  • 读数据
  • 关闭文件
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


void test01()
{
	//1. 包含 <fstream>
	
	//2. 创建流对象
	ifstream ifs;

	//3. 打开文件 并判断是否成功打开
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败! " << endl;
		return;
	}

	//4. 读数据
	

	////第一种 空格终止
	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}

	//第二种 读取一行
	/*char buf[1024] = { 0 };
	while (ifs.getline(buf, sizeof(buf)))
	{
		cout << buf << endl;
	}*/

	//第三种 读取一行
	//string buf;
	//while (getline(ifs, buf))
	//{
	//	cout << buf << endl;
	//}

	//第四种 一个一个读取 效率低
	char c;
	while ((c = ifs.get()) != EOF)	// EOF end of file 文件尾部
	{
		cout << c;
	}


	//5. 关闭文件
	ifs.close();

}


int main()
{
	test01();
	return 0;
}

5.2 二进制文件

打开方式要指定为: ios::binary

5.2.1 写文件

函数原型:ostream& write(const char *buffer,int len);
二进制写文件要用到write

#include <iostream>
#include <fstream>

using namespace std;


class Person
{
public:


	char m_Name[64];
	int m_Age;
};


void test01()
{
	//1. 包含头文件


	//2. 创建流对象同时打开也可以
	ofstream ofs("person.txt", ios::out | ios::binary);

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

	//4. 写文件
	Person p = { "kxq", 18 };
	ofs.write((const char*)&p, sizeof(Person));

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


int main()
{
	test01();
	return 0;
}

5.2.2 读文件

函数原型:istream& read(char *buffer,int len);
二进制写文件要用到read

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


class Person
{
public:

	char m_Name[64];
	int m_Age;
};

void test01()
{
	//1. 包含头文件
	
	//2. 创建流
	ifstream ifs;
	//3. 打开文件
	ifs.open("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "打开文件失败! " << endl;
		return;
	}

	//4. 读文件
	Person p;
	ifs.read((char*)&p, sizeof(Person));


	cout << p.m_Name << " " << p.m_Age << endl;

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


int main()
{

	test01();
	return 0;
}

🎈🎈★,°:.☆( ̄▽ ̄)/$:.°★ 😊


网站公告

今日签到

点亮在社区的每一天
去签到