04章-类和对象--C++核心知识学习笔记
4 类和对象
C++面向对象的三大特性为:封装、继承、多态
C++认为万事万物皆为对象,对象上有其属性和行为
例如:
人可以作为对象,属性有姓名,年龄,身高,体重,行为有走,跑,跳,吃饭,唱歌
车也可以作为对象,属性有偶轮胎,方向盘,车灯,行为有载人,放音乐,开空调
具有相同性质的对象,我们可以抽象为类,人属于人类,车属于车类
4.1 封装
4.1.1 封装的意义
封装是C++面向对象三大特性之一
封装的意义:
- 将属性和行为作为一个整体,表现生活中的事务
- 将属性和行为加以权限控制
封装意义一:
在设计类的时候,属性和行为写在一起,表现事务
语法:class 类名{访问权限: 属性 / 行为};
示例1:设计一个圆类,求圆的周长
示例代码:
#include<iostream> using namespace std; const double PI = 3.1415926; //设计一个圆类,求圆的周长 //圆求周长公式:2*PI*半径 class Circle { //访问权限 //公共权限 public: //圆的属性 int m_r; //圆的行为 //获取圆的周长 double calculateZC() { return 2 * PI * m_r; } }; int main() { //通过圆类 创建具体的圆(对象) Circle c1; //给圆对象 的属性进行赋值 c1.m_r = 10; cout << "圆的周长为:" << c1.calculateZC() << endl; system("pause"); return 0; }
示例2:设计一个学生类,属性有姓名和学号,可以给姓名和学号赋值,可以显示学生的姓名和学号
示例2代码:
#include <iostream> #include <string> using namespace std; //设计一个学生类,属性有姓名和学号 //可以给个姓名和学号赋值,可以显示学生的姓名和学号 //设计学生类 class Student { public://公共权限 //类中的属性和行为统一称为成员 // 属性 成员属性 成员变量 // 行为 成员函数 成员方法 //属性 string m_Name;//姓名 int m_Id;//学号 //行为 //显示姓名和学号 void showStudent() { cout << "姓名:" << m_Name << " 学号:" << m_Id << endl; } //给姓名赋值 void setName(string name) { m_Name = name; } }; int main() { //创建一个具体学生,实例化对象 Student s1; //给s1对象 进行属性赋值操作 s1.m_Name = "zhangsan"; s1.m_Id = 1; //显示学生信息 s1.setName("zhangsan2"); s1.showStudent(); Student s2; s2.m_Name = "lisi"; s2.m_Id = 2; s2.showStudent(); system("pause"); 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 func() { m_Name = "zhangsan"; m_Car = "tuolaji"; m_Password = 123456; } }; int main() { //实例化具体的对象 Person p1; p1.m_Name = "lisi"; //p1.m_Car = "benchi";//错误,保护权限的内容,在类外访问不到 //p1.Password = 123; //错误, 私有权限的内容,类外访问不到 p1.func();//函数也是有权限的,函数体内部是可以访问属性的 system("pause"); return 0; }
4.1.2 struct 和 class 区别
在C++中struct和class唯一区别在于默认的访问权限不同
- struct 默认权限为共有
- class 默认权限为私有
示例:
#include<iostream> using namespace std; class C1 { int m_A;//默认权限是私有 }; struct C2 { int m_A; }; int main() { //struct 和class 区别 C1 c1_class; struct C2 c2_struct; cl_class.m_A;//错误,默认是私有成员 c2_struct.m_A = 100;//正确,默认是共有成员 system("pause"); return 0; }
4.1.3 成员属性设置私有
优点:
- 将所有成员属性设置为私有,可以自己控制读写权限
- 对于写权限,我们可以检测数据的有效性
示例:
#include <iostream> #include <string> using namespace std; //成员属性设置为私有 //优点1:可以自己控制读写权限 //优点2:对于写可以检测数据的有效性 //设计人 类 class Person { public: //写姓名 设置姓名 void setName(string name) { m_Name = name; } //读姓名 获取姓名 string getName() { return m_Name; } //读年龄 获取年龄 int getAge() { m_Age = -1;//初始化为18岁 return m_Age; } //写年龄 设置年龄 void setAge(int age) { if (age < 0 || age > 150) { cout << "您输入的年龄有误!" << endl; return; } m_Age = age; } //写情人 设置情人 void setLover(string lover) { m_Lover = lover; } private: //姓名 可读可写权限 string m_Name; //年龄 只读权限 int m_Age; //情人 只写权限 string m_Lover; }; int main() { Person p; //写姓名 p.setName("zhangsan"); //读姓名 cout << "姓名为:" << p.getName() << endl; //写年龄 p.setAge(1200); //读年龄 cout << "年龄为:" << p.getAge() << endl; //写情人 p.setLover("lisi"); system("pause"); return 0; }
练习案例1:
- 设计立方体类(Cube)
- 求出立方体的面积和体积
- 分别用全局函数和成员函数判断连个立方体是否相等
代码:
#include<iostream> using namespace std; //立方体类设计 //1、设计立方体类 //2、设计属性和行为 //3、设计行为,获取立方体的面积和体积 //4、分别利用全局函数和成员函数,判断两个立方体是否相等 class Cube { public: // 行为 // 设置获取长宽高 // 设置长 void setL(int l) { m_L = l; } // 获取长 int getL() { return m_L; } // 设置宽 void setW(int w) { m_W = w; } // 获取宽 int getW() { return m_W; } // 设置高 void setH(int h) { m_H = h; } // 获取高 int getH() { return m_H; } // 获取立方体面积 int calculateS() { return 2 * m_L * m_W + 2 * m_W * m_H + 2 * m_L * m_H; } //获取立方体体积 int calculateV() { return m_L * m_W * m_H; } //利用成员函数判断两个立方体是否相等 bool isSameByClass(Cube &c) { if (getL() == c.getL() && getW() == c.getW() && getH() == c.getH()) { return true; } else { return false; } } private: //属性 int m_L;//长 int m_W;//宽 int m_H;//高 }; bool isSame(Cube& c1, Cube& c2) { if (c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH()) { return true; } else { return false; } } int main() { //创建立方体对象 Cube c1; c1.setL(10); c1.setH(10); c1.setW(10); //600 cout << "c1 的面积为:" << c1.calculateS() << endl; //1000 cout << "c1 的体积为:" << c1.calculateV() << endl; //创建第二个立方体 Cube c2; c2.setH(10); c2.setL(10); c2.setW(10); //利用全局函数判断 bool ret = isSame(c1, c2); if (ret) { cout << "c1 和 c2是相等的!" << endl; } else { cout << "c1 和 c2是不相等的!" << endl; } //利用成员函数判断 ret = c1.isSameByClass(c2); if (ret) { cout << "c1 和 c2是相等的!" << endl; } else { cout << "c1 和 c2是不相等的!" << endl; } system("pause"); return 0; }
练习案例2:
设计一个圆形类(Circle),和一个点类(Point),计算点和圆的关系
点和圆关系判断:
- 点到圆心的距离 == 半径,点在圆上
- 点到圆心的距离 > 半径,点在圆外
- 点到圆心的距离 < 半径,点在源内
代码:
#include<iostream> using namespace std; //点和圆的关系案例 // 点类 class Point { private: int m_X; int m_Y; public: //设置x void setX(int x) { m_X = x; } //获取x int getX() { return m_X; } //设置y void setY(int y) { m_Y = y; } //获取y int getY() { return m_Y; } }; //圆类 class Circle { public: //设置半径 void setR(int r) { m_R = r; } //获取半径 int getR() { return m_R; } //设置圆心 void setCenter(Point center) { m_Center = center; } //获取圆心 Point getCenter() { return m_Center; } private: int m_R;//半径 //在类中可以让另一个类,作为本类中的成员 Point m_Center;//圆心 }; //判断点和圆关系函数 void isInCircle(Circle& c, Point& p) { //计算两点之间距离的平方 int distence = (c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) + (c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY()); //计算半径的平方 int rDistance = c.getR() * c.getR(); //判断关系 if (distence == rDistance) { cout << "点在圆上" << endl; } else if(distence > rDistance) { cout << "点在圆外" << endl; } else { cout << "点在园内" << endl; } } int main() { //创建一个圆 Circle c; c.setR(10); Point center; center.setX(10); center.setY(0); c.setCenter(center); //创建一个点 Point p; p.setX(10); p.setY(10); //判断他们的关系 isInCircle(c, p); system("pause"); return 0; }
代码2:分文件写
main.cpp:
#include<iostream> using namespace std; #include "circle.h" #include "point.h" //判断点和圆关系函数 void isInCircle(Circle& c, Point& p) { //计算两点之间距离的平方 int distence = (c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) + (c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY()); //计算半径的平方 int rDistance = c.getR() * c.getR(); //判断关系 if (distence == rDistance) { cout << "点在圆上" << endl; } else if (distence > rDistance) { cout << "点在圆外" << endl; } else { cout << "点在园内" << endl; } } int main() { //创建一个圆 Circle c; c.setR(10); Point center; center.setX(9); center.setY(0); c.setCenter(center); //创建一个点 Point p; p.setX(10); p.setY(10); //判断他们的关系 isInCircle(c, p); system("pause"); return 0; }
point.cpp:
#include "point.h" //设置x void Point::setX(int x) { m_X = x; } //获取x int Point::getX() { return m_X; } //设置y void Point::setY(int y) { m_Y = y; } //获取y int Point::getY() { return m_Y; }
point.h:
#pragma once //防止头文件重复包含 #include <iostream> using namespace std; // 点类 class Point { private: int m_X; int m_Y; public: //设置x void setX(int x); //获取x int getX(); //设置y void setY(int y); //获取y int getY(); };
circle.cpp:
#include "circle.h" //设置半径 void Circle::setR(int r) { m_R = r; } //获取半径 int Circle::getR() { return m_R; } //设置圆心 void Circle::setCenter(Point center) { m_Center = center; } //获取圆心 Point Circle::getCenter() { return m_Center; }
circle.h:
#pragma once //防止同文件重复包含 #include <iostream> //标准输入输出流 using namespace std; #include "point.h" //圆类 class Circle { public: //设置半径 void setR(int r); //获取半径 int getR(); //设置圆心 void setCenter(Point center); //获取圆心 Point getCenter(); private: int m_R;//半径 //在类中可以让另一个类,作为本类中的成员 Point m_Center;//圆心 };
4.2 对象的初始化清理
- 生活中我们买的电子产品都基本会有出厂设置,在某一天我们不用时候也会删除一些自己信息数据保证安全
- C++中的面向对象来源于生活,每个对象也都会有初始化设置以及对象销毁前的清理数据设置。
4.2.1 构造函数和析构函数
对象的初始化和清理而言是两个非常重要的安全问题
- 一个对象或者变量没有初始状态,对其使用后果是未知的
- 同样的使用完一个对象或变量,没有及时清理,也会造成一定的安全问题
C++利用了构造函数和析构函数解决上述问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。对象的初始化和清理工作是编译器强制要求我们做的事情,因此如果我们不提供构造和析构,编译器会提供编译器提供的构造和函数和析构函数是空实现。
- 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无需手动调用
- 析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作
构造函数语法:类名(){}
- 构造函数,没有返回值也不写void
- 函数名称与类名相同
- 构造函数可以由有参数,因此可以发生重载
- 程序在调用对象时候会自动调用构造,无需手动调用,而且只会调用一次
析构函数语法:~类名(){}
- 析构函数,没有返回值也不写void
- 函数名称与类名相同,在名称前加上符号~
- 析构函数不可以有参数,因此不可以发生重载
- 程序在对象销毁前会自动调用析构函数,无需手动调用,而且只会调用一次
示例:
#include <iostream> using namespace std; //对象的初始化和清理 //1、构造函数,继续初始化操作 class Person { public: //1、构造函数 //没有返回值,不用写void //函数名 与类名相同 //构造函数可以有参数,可以发生重载 //创建对象的时候,构造函数会自动调用,而且只调用一次 Person() { cout << "Person 构造函数的调用" << endl; } //2、析构函数,进行清理的操作 //没有返回值,不写void //函数名和类名相同, 在名称前加~ //析构函数不可以有参数的,不可以发生重载 //对象在销毁前,会自动调用析构函数,而且只会调用一次 ~Person() { cout << "Person 析构函数的调用" << endl; } }; //构造和析构都是必须有的实现,如果我们自己不提供,编译器会提供一个空实现的构造和析构 void test01() { Person p;//在栈上的数据,test01执行完毕后,释放这个对象 } int main() { test01(); Person p;//析构是在对象执行完成后才会执行 system("pause"); return 0; }
4.2.2 构造函数的分类和调用
两种分类方式:
- 按参数分类:有参构造和无参构造
- 按类型分类:普通构造和拷贝构造
三种调用方式:
- 括号法
- 显示法
- 隐式转换法
示例:
#include<iostream> using namespace std; //1构造函数的分类及调用 //分类 //按照参数分类 无参构造(默认构造) 和 有参构造 //按照类型分类 普通构造 拷贝构造 class Person { public: //构造函数 Person() { cout << "Person 无参构造函数的调用" << endl; } Person(int a) { age = a; cout << " Person 有参构造函数的调用" << endl; } //拷贝构造函数 Person(const Person &p) // 规定写法 { //将传入的人身上的所有属性,拷贝到我身上 age = p.age; cout << " Person 拷贝构造函数的调用" << endl; } //析构函数 ~Person() { cout << "Person 析构函数的调用" << endl; } int age; }; //调用 void test01() { //1、括号法 推荐这种 Person p1; //默认构造函数调用 Person p2(10);//有参构造函数调用 Person p3(p2);//拷贝构造函数调用 cout << "p2 的年龄为: " << p2.age << endl; cout << "p3 的年龄为: " << p3.age << endl; //注意事项1 //调用默认构造函数的时候,不要加() Person p11();//这行代码编译器会认为是一个函数的声明,不会认为在创建对象 //2、显示法 Person p4;//无参构造,默认构造 Person p5 = Person(10);//有参构造 Person p6 = Person(p5);//拷贝构造 Person(10);//匿名对象,特点:当前行执行结束后,系统会立即回收掉匿名对象 cout << "aaa" << endl;//是在上一个匿名对象析构函数调用后才打印aaa //注意事项2 //不要利用拷贝构造函数 初始化匿名对象 //Person(p5);//编译器会认为Person(p3) == Person P3; 会认为是对象的声明 //3、隐式转换法 Person p7 = 10; //有参构造,相当于写了Person p7 = Person(10); Person p8 = p4; //拷贝构造 } int main() { test01(); system("pause"); return 0; }
4.2.3 拷贝构造函数调用时机
C++中拷贝构造函数调用时机通常由三种情况
- 使用一个已经创建完毕的对象来初始化一个新对象
- 值传递的方式给函数参数传值
- 以值方式返回局部对象
示例:
#include <iostream> using namespace std; //拷贝构造函数调用时机 //1、使用一个已经创建完毕的对象来初始化一个新对象 //2、值传递的方式给函数参数传值 //3、值方式返回局部对象 class Person { public: Person() { cout << "Person 默认构造函数调用" << endl; } Person(int age) { m_Age = age; cout << "Person 有参函数调用" << endl; } Person(const Person & p) { cout << "Person 拷贝构造函数调用" << endl; m_Age = p.m_Age; } ~Person() { cout << "Person 析构函数调用" << endl; } int m_Age; }; //1、使用一个已经创建完毕的对象来初始化一个新对象 void test01() { Person p1(20); Person p2(p1); cout << "p2 的年龄为:" << p2.m_Age << endl; } //2、值传递的方式给函数参数传值 void doWork(Person p) { } void test02() { Person p; doWork(p); } //3、值方式返回局部对象 Person doWork2() { Person p1; cout << (int*)&p1 << endl; return p1; } void test03() { Person p = doWork2(); cout << (int*)&p << endl; } int main() { test01(); test02(); test03(); system("pause"); return 0; }
4.2.4 构造函数调用规则
默认情况下,C++编译其至少给一个类添加三个函数
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝析构函数,对属性进行值拷贝
构造函数默调用规则如下:
- 如果用户定义有参构造函数,C++不再提供默认无参构造函数,但是会提供默认拷贝构造
- 如果用户定义拷贝构造函数,C++不再提供其他构造函数
示例:
#include<iostream> using namespace std; //构造函数的调用规则 //1、创建一个类,C++编译器会给每个类都添加至少三个函数 //默认构造 (空实现) //析构函数 (空实现) //拷贝构造 (值拷贝) class Person { public: Person() { cout << "Person 的默认构造函数调用" << endl; } Person(int age) { cout << "Person 的有参构造函数调用" << endl; m_Age = age; } Person(const Person& p) { cout << "Person 的拷贝构造函数调用" << endl; m_Age = p.m_Age; } ~Person() { cout << "Person 的析构函数调用" << endl; } int m_Age; }; void test01() { Person p; p.m_Age = 18; Person p2(p); cout << "p2 的年龄为:" << p2.m_Age << endl; } void test02() { Person p; } int main() { //test01(); test02(); system("pause"); return 0; }
4.2.5 深拷贝与浅拷贝
深浅拷贝是面试经典问题,也是常见的一个坑
- 深拷贝:在堆区重新申请空间,进行拷贝操作
- 浅拷贝:简单的赋值拷贝操作
示例:
#include <iostream> using namespace std; //深拷贝与浅拷贝 class Person { public: Person() { cout << "Person 的默认构造函数调用" << endl; } Person(int age, int height) { m_Age = age; m_Height = new int(height);//利用new把数据创建在堆区 cout << "Person 的有参构造函数调用" << endl; } //自己实现拷贝构造函数 解决浅拷贝带来的问题 Person(const Person& p) { cout << "Person 拷贝构造函数的调用" << endl; m_Age = p.m_Age; //m_Height = p.m_Height;//编译器默认实现的就是浅拷贝这行代码 //深拷贝操作 m_Height = new int(*p.m_Height);//在堆区深拷贝,用new } ~Person() { //析构代码,将堆区开辟数据做释放操作 if (m_Height != NULL) { delete m_Height; m_Height = NULL; } cout << "Person 的析构函数调用" << endl; } int m_Age;//年龄 int* m_Height;//身高 }; void test01() { Person p1(18, 178); cout << "p1的年龄为:" << p1.m_Age <<" 身高为:"<< *p1.m_Height<< endl; Person p2(p1); cout << "p2的年龄为:" << p2.m_Age << " 身高为:" << *p2.m_Height << endl; } int main() { test01(); system("pause"); return 0; }
4.2.6 初始化列表
作用:
C++提供了初始化列表语法,用来初始化属性
语法:
构造函数():属性1(值1),属性2(值2)...{}
示例:
#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(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(100,20,30); cout << "m_A = " << p.m_A << endl; cout << "m_B = " << p.m_B << endl; cout << "m_B = " << p.m_C << endl; } int main() { test01(); system("pause"); return 0; }
4.2.7 类对象作为类成员
C++类中的成员可以是另一个类的对象,我们称该成员为 对象成员
例如
class A {}; class B { A a; };
B类中由对象A作为成员,A为对象成员
那么当创建B对象时,A与B的构造和析构的顺序是谁先谁后?
示例:
#include<iostream> #include<string> using namespace std; //类对象作为类成员 //手机类 class Phone { public: Phone(string pName) { cout << "Phone 的构造函数调用" << endl; m_PName = pName; } ~Phone() { cout << "Phone 的析构函数调用" << endl; } //手机品牌名称 string m_PName; }; //人类 class Person { public: //Phone m_Phone = pName; 隐式转换法 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("ZhagnSan", "iPhone13"); cout << "姓名为:" << p.m_Name << "\t"; cout << "手机为:" << p.m_Phone.m_PName << endl; } int main() { test01(); system("pause"); return 0; }
结论:
- 当其他类的对象作为本类成员,先构造类的对象,再构造自身
- 析构顺序:先释放自身,再释放构造类的对象
4.2.8 静态成员
静态成员就是再成员变量和成员函数前加上关键字static,成为静态成员
静态成员分为:
- 静态成员变量
- 所有对象共享同一份数据
- 在编辑阶段分配内存
- 类内声明,类外初始化
- 静态成员函数
- 所有对象共享同一函数
- 静态成员函数只能访问静态成员变量
示例1:
#include<iostream> using namespace std; //静态成员变量 class Person { public: //1、所有对象都共享同一份数据 //2、编译阶段就分配内存 //3、类内声明,类外初始化操作 static int m_A; //静态成员变量是有访问权限的 private: static int m_B; }; int Person::m_A = 100; int Person::m_B = 200; void test01() { Person p; cout << p.m_A << endl; Person p2; p2.m_A = 200; //100?200 cout << p.m_A << endl; } void test02() { //静态成员变量 不属于某个对象上 所有对象都共享同一份数据 //因此静态成员变量有两种访问方式 //1、通过对象进行访问 Person p; cout << p.m_A << endl; //2、通过类名进行访问 cout << Person::m_A << endl; //cout << Person::m_B << endl; //错误。类外访问私有的。 } int main() { //test01(); test02(); system("pause"); return 0; }
示例2:
#include <iostream> using namespace std; //静态成员函数 //所有对象共享同一个函数 //静态成员函数只能访问静态成员变量 class Person { public: //静态成员函数 static void func() { m_A = 100;//静态成员函数能够访问静态成员变量 //m_B = 200;//错误,静态成员函数,不可以访问,非静态成员变量,无法区分到底是哪个对象的数据 cout << "static void func 调用" << endl; } static int m_A;//静态成员变量 int m_B; //静态成员函数也是有访问权限的 private: static void func2() { cout << "static void func2 调用" << endl; } }; int Person::m_A = 10; void test01() { //1、通过对象访问 Person p; p.func(); //2、通过类名访问 Person::func(); //Person::func();//错误,类外访问不到私有静态成员函数 } int main() { test01(); system("pause"); 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 func(){} //非静态成员函数 //不属于类的对象上 static void func2() {}//静态成员函数 //不属于类的对象上 }; void test01() { Person p; //空对象占用内存空间为:1 //C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置 //每个空对象也应该有一个独一无二的内存地址 cout << "size of p = " << sizeof(p) << endl; } void test02() { Person p; //空对象占用内存空间为:4 cout << "size of p = " << sizeof(p) << endl; } int main() { test01(); test02(); system("pause"); return 0; }
4.3.2 this指针概念
通过4.3.1我们知道C++中成员变量和成员函数是分开存储的,每个非静态成员函数只会诞生一份函数示例,也就是说多个同类型的对象共用一块代码,那么问题来:这一块代码是如何区分哪个对象调用自己的呢?
C++通过提供特殊的对象指针,this指针,解决上述问题。this指针指向被调用的成员函数所属的对象
- this指针是隐含每一个非静态成员函数内的一种指针
- this指针不需要定义,直接使用即可
this指针的用途:
- 当形参和成员变量同名时,可用this指针来区分
- 在类的非静态成员函数中返回对象本身,可使用 return *this
示例:
#include<iostream> using namespace std; class Person { public: Person(int age) { //this指针 指向 被调用成员函数 所属的对象 this->age =age; } Person& PersonAddAge(Person &p) { this->age += p.age; //this 指向p2的指针,而*this指向的就是p2这个对象本体 return *this; } int age;//m is member }; //1、解决名称冲突 void test01() { Person p1(18); cout << "p1 的年龄是多少:" << p1.age << endl; } //2、返回对象本身用*this void test02() { Person p1(10); Person p2(10); //链式编程思想 p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1); cout << "p2 的年龄为:" << p2.age << endl; } int main() { test01(); test02(); system("pause"); return 0; }
4.3.3 空指针访问成员函数
C++中空指针也是可以调用成员函数的,但是也要注意没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
代码:
#include<iostream> using namespace std; class Person { public: void showClassName() { cout << "this is Person class" << endl; } void showPersonAge() { //报错原因是,传入的指针为NULL if (this == NULL) { return; } cout << "age = " << this->m_Age << endl; } int m_Age; }; void test01() { Person* p = NULL;//空指针,并没有确定的对象,访问不到 p->showClassName(); p->showPersonAge(); } int main() { test01(); system("pause"); return 0; }
4.3.4 const修饰成员函数
常函数:
- 成员函数后加const后我们称这个函数为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
- 声明对象前加const称该对象为常对象
- 常对象只能调用常函数
示例:
#include <iostream> using namespace std; //常函数 class Person { public: //this指针本质,是指针常量,指针的指向是不可以修改的 //Person * const this; //const修改this所以this不允许修改 //const Person * const this; //const修改this所以this不允许修改 //在成员函数后面加const ,修饰的this指针,让指针指向的值也不可以修改 void showPerson() const //相当于 const Person *//该为常函数 { //this->m_A = 100; //this = NULL;//报错,this指针不可以修改指针指的指向 this->m_B = 100; } int m_A; mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值,加上关键字mutable就可以修改了 void func() { } }; void test01() { Person p; p.showPerson(); } //常对象 void test02() { const Person p;//在对象前加const ,变为常对象 //p.m_A = 100;//报错,不允许修改的。 p.m_B = 100;//不报错,可以修改,因为有mutable修饰, //常对象只能调用常函数 p.showPerson();//不报错,只能调用常函数 //p.func();//报错,不可以调用这个,因为普通函数里面的值可以修改 } int main() { system("pause"); return 0; }
4.4
生活中你的家有客厅(Public),有你的卧室(Private),客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去,但是呢,你也可以允许你的好闺蜜基友进去。
在程序里,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术,友元的目的就是让一个函数或者类访问另一个类中私有成员
友元关键字为friend
友元的三种实现:
- 全局函数做友元
- 类做友元
- 成员函数做友元
4.4.1 全局函数做友元
示例:
#include <iostream> #include <string> using namespace std; //定义类 class Building { //goodGay全局函数是Building好朋友,可以访问Building中的私有成员 friend void goodGay(Building* building); public: Building() { m_SittingRoom = "Sittingroom"; m_BedRoom = "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 building; goodGay(&building); } int main() { test01(); system("pause"); return 0; }
4.4.2 类做友元
示例:
#include<iostream> #include<string> using namespace std; //类做友元 class Building; class GoodGay{ public: void visit();//参观函数访问Building中的属性 GoodGay(); Building* building; }; class Building { //GoodGay是本类的好朋友,可以访问该类的私有成员 friend class GoodGay; public: string m_Sittingroom; Building(); private: string m_Bedroom; }; //类外写成员函数 Building::Building() { m_Sittingroom = "客厅"; m_Bedroom = "卧室"; } GoodGay::GoodGay() { //创建一个Building的对象 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; }
4.4.3 全局函数做友元
示例:
#include<iostream> #include<string> using namespace std; class Building; class GoodGay { public: GoodGay(); void visit();//让visit可以访问Building中私有成员 void visit2();//让visit2不可以访问Building中私有成员 Building* building; }; class Building { //告诉编译器,GoodGay类下的visit成员函数作为本类的好朋友,可以访问私有成员 friend void GoodGay::visit(); public: Building(); public: string m_Sittingroom; private: string m_Bedroom; }; //类外实现 Building::Building() { m_Sittingroom = "Sittingroom"; m_Bedroom = "Bedroom"; } GoodGay::GoodGay() { building = new Building; } void GoodGay::visit() { cout << "visit 函数正在访问:" << building->m_Sittingroom << endl; cout << "visit 函数正在访问:" << building->m_Bedroom << endl; } void GoodGay::visit2() { cout << "visit2 函数正在访问:" << building->m_Sittingroom << endl; //cout << "visit 函数正在访问:" << building->m_Bedroom << endl;//报错,访问不了 } void test01() { GoodGay gg; gg.visit(); gg.visit2(); } int main() { test01(); system("pause"); return 0; }
4.5 运算符重载
运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
4.5.1 加号运算符重载
作用:实现两个自定义数据类型相加的运算
对于内置的数据类型:编译器知道如何运算
示例:
#include<iostream> using namespace std; //加号运算符重载 class Person { public: //1、成员函数重载+号 Person operator+(Person& p) { Person temp; temp.m_A = this->m_A + p.m_A; temp.m_B = this->m_A + p.m_B; return temp; } int m_A; int m_B; }; //2、全局函数重载+号 Person operator+(Person& p1, Person& p2) { Person temp; temp.m_A = p1.m_A + p2.m_A; temp.m_B = p1.m_B + p2.m_B; return temp; } //函数重载版本 Person operator+(Person& p1, int num) { Person temp; temp.m_A = p1.m_A + num; temp.m_B = p1.m_B + num; return temp; } 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; //运算符重载,也可以发生函数重载 Person p4 = p1 + 10; cout << "p3.m_A = " << p3.m_A << endl; cout << "p3.m_B = " << p3.m_B << endl; } int main() { test01(); system("pause"); return 0; }
总结:
- 对于内置的数据类型的表达式的运算符不可以改变的
- 不要滥用运算符重载
4.5.2 左移运算符重载
作用:可以输出自定义的数据类型
示例:
#include <iostream> using namespace std; //左移运算符重载技术 class Person { friend ostream& operator<<(ostream& cout, Person& p); private: ////利用成员函数重载左移运算符 // 通常不会利用成员函数重载左移运算符,无法实现cout在左侧 //void operator<<(cout) //{ //} int m_A; int m_B; public: Person(int a, int b) { m_A = a; m_B = b; } }; //利用全局函数重载左移运算符 ostream& operator<<(ostream &cout, Person &p)//本质operator(cout ,p) 简化 cout <<p { cout << "m_A = " << p.m_A << " m_B = " << p.m_B; return cout; } void test01() { Person p(10,10); cout << p << endl;; } int main() { test01(); system("pause"); return 0; }
4.5.3 递增运算符重载
作用:通过重载递增运算符,实现自己的整形数据
示例:
#include <iostream> using namespace std; //重载递增运算符 //自定义的整型变量 class MyInteger { friend ostream& operator<<(ostream& cout, MyInteger myint); public: MyInteger() { m_Num = 0; } //重载前置++运算符 //返回引用是为了一直对一个数据进行操作 MyInteger& operator++()//返回引用,而不是返回值,所以加& { //先进行++运算 m_Num++; //再将自身做返回 return *this; } //重载后置++运算符 //int 代表占位参数,可以用于区分前置和后置递增 //此处需要返回一个值,不能返回一个引用,后置递增返回值 MyInteger operator++(int)//int 可以不用填 只能写int,用于区分前置和后置 { //先 记录当时结果 MyInteger temp = *this; //后 递增 m_Num++; //最后 将记录结果做返回 return temp; } 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; } void test02() { MyInteger myint; cout << myint++ << endl; cout << myint << endl; } int main() { test01(); test02(); system("pause"); 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; m_Age = NULL; } } //重载 赋值运算符 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); p3 = p2 = p1;//赋值操作 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 = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; system("pause"); 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; } return false; } //重载!=符号 bool operator!=(Person& p) { if (this->m_Name != p.m_Name || this->m_Age != p.m_Age) { return true; } return false; } string m_Name; int m_Age; }; void test01() { Person p1("Tom", 18); Person p2("Tom", 19); 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(); system("pause"); return 0; }
4.5.6 函数调用运算符重载
- 函数调用运算符()也可以重载
- 由于重载后使用的方式非常像函数的调用,因此成为仿函数
- 仿函数没有固定写法,非常的灵活
示例:
#include <iostream> #include <string> using namespace std; //函数调用运算符重载 //打印输出类 class MyPrint { public: //重载函数调用运算符 void operator()(string test) { cout << test << endl; } }; //定义函数 void MyPrint02(string test) { cout << test << endl; } void test01() { MyPrint myprint; myprint("hello world!");//由于使用起来非常类似函数调用,因此称为仿函数 MyPrint02("hello world!"); } //仿函数非常的灵活,没有固定的写法 //加法类 class MyAdd { public: int operator()(int num1, int num2) { return num1 + num2; } }; void test02() { MyAdd myadd; int ret = myadd(100, 100); cout << "ret = " << ret << endl; //匿名函数对象 cout << MyAdd()(100, 100) << endl; } int main() { test01(); test02(); system("pause"); return 0; }
4.6 继承
继承是面向对象三大特性之一:有些类与类之间存在特殊的关系,定义这些类时,下级别的成员除了拥有上一级的共性,还有自己的特性,这个时候我们可以考虑利用继承的技术,减少重复的代码
4.6.1 继承的基本语法
例如我们看到很多网站中,都有公共的头部,公共的底部,甚至公共的左侧列表,只有中心内容不同,接下来我们分别利用普通写法和继承的写法来实现网页中的内容,看一下继承存在的意义以及好处
普通实现示例:
#include<iostream> using namespace std; //普通实现页面 //Java页面 class Java { public: void header() { cout << "首页、公开课、登录、注册...(公共头部)" << endl; } void footer() { cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl; } void left() { cout << "Java、Python、C++、...(公共分类列表)" << endl; } void content() { cout << "Java视频内容" << endl; } }; //C++页面 class Cpp { public: void header() { cout << "首页、公开课、登录、注册...(公共头部)" << endl; } void footer() { cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl; } void left() { cout << "Java、Python、C++、...(公共分类列表)" << endl; } void content() { cout << "C++视频内容" << endl; } }; //Python页面 class Python { public: void header() { cout << "首页、公开课、登录、注册...(公共头部)" << endl; } void footer() { cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl; } void left() { cout << "Java、Python、C++、...(公共分类列表)" << endl; } void content() { cout << "Python视频内容" << endl; } }; void test01() { cout << "Java下载视频的页面如下:" << endl; Java ja; ja.header(); ja.footer(); ja.left(); ja.content(); cout << "==============" << endl; cout << "C++下载视频的页面如下:" << endl; Cpp cpp; cpp.header(); cpp.footer(); cpp.left(); cpp.content(); cout << "==============" << endl; cout << "Python下载视频的页面如下:" << endl; Python py; py.header(); py.footer(); py.left(); py.content(); cout << "=============" << endl; } int main() { test01(); system("pause"); return 0; }
继承实现示例:
#include <iostream> using namespace std; class BasePage { public: void header() { cout << "首页、公开课、登录、注册...(公共头部)" << endl; } void footer() { cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl; } void left() { cout << "Java、Python、C++、...(公共分类列表)" << endl; } }; //继承的好处:减少重复的代码 // 语法 class 子类:继承方式 父类 // 子类也称为 派生类 // 父类也称为 基类 //Java 页面 class Java :public BasePage { public: void content() { cout << "Java视频内容" << endl; } }; //Python 页面 class Python : public BasePage { public: void content() { cout << "Python视频内容" << endl; } }; //C++ 页面 class Cpp : public BasePage { public: void content() { cout << "C++视频内容" << endl; } }; void test01() { cout << "Java下载视频的页面如下:" << endl; Java ja; ja.header(); ja.footer(); ja.left(); ja.content(); cout << "==============" << endl; cout << "C++下载视频的页面如下:" << endl; Cpp cpp; cpp.header(); cpp.footer(); cpp.left(); cpp.content(); cout << "==============" << endl; cout << "Python下载视频的页面如下:" << endl; Python py; py.header(); py.footer(); py.left(); py.content(); cout << "=============" << endl; } int main() { test01(); system("pause"); return 0; }
4.6.2 继承方式
继承的语法:class 子类: 继承方式 父类
继承方式一共有三种:
- 公共继承:不可以访问private,在public和protected保持一致
- 保护继承:不可以访问private,public和protected变成protected
- 私有继承:不可以访问private,public和protected变成private
示例:
#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 func() { m_A = 10;//父类中公共权限内容到子类中依旧是公共权限 m_B = 10;//父类中保护权限内容到子类总依旧是保护权限 //m_C = 10;//报错,父类中私有权限,子类访问不到 } }; void test01() { son1 s1; s1.m_A = 100; //s1.m_B = 100;//报错,到Son1中m_B是保护权限,类外访问不到 } //保护继承 class son2 :protected Base1 { public: void func() { m_A = 100;//父类中公有成员,到子类中变成保护权限 m_B = 100;//父类中保护权限,到子类中变成保护权限 //m_C = 100;//报错,父类中的私有成员,子类访问不到 } }; void test02() { son2 s2; //s2.m_A = 100;//报错,son2中 m_A变成保护权限,因此类外访问不到 //s2.m_B = 100;//报错,son2中 m_B也是保护权限,因此类外访问不到 //s2.m_C = 100;//报错, } class son3 :private Base1 { public: void func() { m_A = 100;//父类中共有成员,到子类中变成私有成员 m_B = 100;//父类中保护成员,到子类中变成私有成员 //m_C = 100;//报错,父类中的私有成员,子类访问不到 } }; void test03() { son3 s3; //s3.m_A = 100;//报错,son2中 m_A变成私有成员,因此类外访问不到 //s3.m_B = 100;//报错,son2中 m_B也是私有成员,因此类外访问不到 //s3.m_C = 100;//报错, } class GrandSon3 :public son3 { public: void func() { //m_A = 100;//报错,因为父类中私有成员,子类访问不到 //m_B = 100//报错,因为父类中私有成员,子类访问不到 //m_C = 100;//报错,因为父类中私有成员,子类访问不到 } }; int main() { system("pause"); 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; }; //利用开发人员命令提示工具查看对象模型 //跳转盘符 //跳转文件路径cd 具体路径 //c1 /d1 reportSingleClassLayout类名 文件名 void test01() { //16 //父类中所有非静态成员属性都会被子类继承下去 //父类中私有成员属性,是被编译器隐藏了,因此访问不到,但是确实被继承下去了 cout << "size of Son = " << sizeof(Son) << endl; } int main() { test01(); system("pause"); 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() { //Base b; Son s; } //先有父类构造,再有子类构造,再子类析构,再父类析构 int main() { test01(); system("pause"); return 0; }
4.6.5 继承同名成员处理方式
问题:当子类和父类出现同名的成员,如何通过子类对象,访问到子类或父类中同名的数据呢?
答:
- 访问子类同名成员 直接访问即可
- 访问父类同名成员 需要加作用域
示例:
#include <iostream> using namespace std; //继承中同名成员处理 class Base { public : Base() { m_A = 100; } int m_A; void func() { cout << "Base - func()函数调用" << endl; } void func(int a) { cout << "Base - func(int a)函数调用" << endl; } }; class Son :public Base { public: Son() { m_A = 200; } int m_A; void func() { cout << "Son - func()函数调用" << endl; } }; //同名成员属性处理 void test01() { Son s; //如果出现同名是直接调用就是子类中的 cout << "Son中 m_A = " << s.m_A << endl; //如果通过子类对象访问到父类中的同名成员,需要加父类的作用域 cout << "Base 中 m_A = " << s.Base::m_A << endl; } //同名成员函数处理 void test02() { Son s; //如果出现同名是直接调用就是子类中的 s.func(); //如果通过子类对象访问到父类中的同名成员,需要加父类的作用域 s.Base::func(); //如果子类中出现同名函数,子类中会隐藏掉所有的父类同名函数 //如果想要访问到父类中被隐藏的同名成员函数,需要加作用域 s.Base::func(10); } int main() { test01(); test02(); system("pause"); return 0; }
总结
- 子类对象可以直接访问子类中同名成员
- 子类对象加作用域可以访问到父类同名成名
- 当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类同名函数
4.6.6 继承同名静态成员处理方式
问题:继承中同名的静态成员在子类对象上如何进行访问?
静态成员和非静态成员出现同名,处理方式一致
- 访问子类同名成员 直接访问即可
- 访问父类同名成员 需要加作用域
示例:
#include <iostream> using namespace std; //继承中的同名静态成员处理方式 class Base { public: static int m_A;//静态成员 static void func() { cout << "Base -static vodi func()" << endl; } static void func(int a) { cout << "Base -static vodi func(int a)" << endl; } }; int Base::m_A = 100;//类内定义,类外初始化 class Son :public Base { public: static int m_A;// static void func() { cout << "Son -static vodi func()" << endl; } }; int Son::m_A = 200; void test01() { //1、通过对象访问 cout << "通过对象访问:" << endl; Son s; cout << "Son 中 m_A = " << s.m_A << endl; cout << "Base 中 m_A = " << s.Base::m_A << endl; //2、通过类名访问 cout << "通过类名访问:" << endl; cout << "Son 中 m_A = " << Son::m_A << endl; cout << "Base 中 m_A = " << Son::Base::m_A << endl; } //同名静态成员函数 void test02() { Son s; //1、通过对象访问 cout << "通过对象访问:" << endl; s.func(); s.Base::func(); //2、通过类名访问 cout << "通过类名访问:" << endl; Son::func(); Son::Base::func(); Son::Base::func(10); } int main() { test01(); test02(); system("pause"); return 0; }
总结:同名静态成员处理方式和非静态处理方式一致,只不过有两种访问的方式(通过对象和通过类名)
4.6.7 多继承语法
C++允许一个类继承多个类
语法:class 子类: 继承方式 父类1, 继承方式 父类2...
多继承可能会引发父类中同名成员出现,需要加作用域区分
C++实际开发中不建议多继承
示例:
#include<iostream> using namespace std; //多继承语法 class Base1 { public: Base1() { m_A = 100; } int m_A = 100; }; class Base2 { public: Base2() { m_A = 200; m_B = 200; } int m_B = 100; int m_A = 200; }; //子类 需要继承Base1 和 Base 2 class Son :public Base1, public Base2 { public: Son() { m_C = 300; m_D = 400; } int m_C = 300; int m_D = 400; }; void test01() { Son s; cout << "size of Son = " << sizeof(s) << endl; //当父类中出现同名的成员,需要加作用域 cout << "Base1 中 m_A = " << s.Base1::m_A << endl; cout << "Base2 中 m_A = " << s.Base2::m_A << endl; } int main() { test01(); system("pause"); return 0; }
总结:多继承中如果父类出现了同名情况,子类使用时候要加作用域
4.6.8
菱形继承:
- 两个派生类继承同一个基类。
- 又有某个类同时继承这两个派生类。
- 这种继承被称为菱形继承,或者钻石继承。
问题:
- 羊继承了动物的数据,驼继承了动物的数据,当羊驼使用数据时,就会产生二义性
- 羊驼继自动物的数据继承了两份,其实我们应该清楚,这份数据只需要一份就够可以。
代码:
#include<iostream> using namespace std; //动物类 class Animal { public: int m_Age; }; // 利用虚继承,解决菱形继承问题 // 继承之前 加上关键字 virtual 变成虚继承 // Animal 类称为虚基类 // 羊类 class Sheep :virtual public Animal {}; //驼类 class Camel :virtual public Animal {}; class SheepCamel : public Sheep, public Camel {}; void test01() { SheepCamel st; st.Sheep::m_Age = 18; st.Camel::m_Age = 28; //当菱形继承,两个父类拥有相同数据,需要加以作用域区分 cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl; cout << "st.Camel::m_Age = " << st.Camel::m_Age << endl; cout << "st.m_Age = " << st.m_Age << endl; //这份数据我们知道,只有有一份就可以,菱形继承导致数据有两份,浪费资源 } int main() { test01(); system("pause"); return 0; }
总结:
- 菱形继承带来的问题主要是子类继承两份相同的数据,导致资源浪费以及毫无意义
- 利用虚继承可以解决菱形继承问题
4.7多态
4.7.1 多态的基本概念
多态是C++面向对象三大特性之一:
多态分为两类:
- 静态多态:函数重载和运算符重载属于静态多态,复用函数名
- 动态多态:派生类和虚函数实现运行时多态
金泰多态和动态多态区别:
- 静态多态的函数地址早绑定,编译阶段确定函数地址
- 动态多态的函数地址晚绑定,运行阶段确定函数地址
示例:
#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; } }; //执行说话的函数 //地址早绑定,在编译阶段确定函数地址 //如果想要猫说话,那么这个函数地址不能提前绑定,需要在函数执行阶段进行绑定,实行晚绑定 void doSpeak(Animal &animal)//父类可以直接指向子类 { animal.speak(); } void test01() { Cat cat; doSpeak(cat); Dog dog; doSpeak(dog); } int main() { test01(); system("pause"); return 0; }
总结:
- 有继承关系
- 子类重写父类的虚函数
- 父类指针指向或引用指向子类对象
重写:函数返回值类型,函数名,参数列表,完全一致
4.7.2 多态案例1-计算器类
案例描述:分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类
多态的优点:
- 代码组织结构清晰
- 可读性强
- 利于前期和后期的扩展以及维护
示例:
#include<iostream> #include<string> using namespace std; //分别利用普通写法和多态技术实现计算器 //普通写法 class Calculator { public: int getResult(string oper) { if (oper == "+") { return m_Num1 + m_Num2; } else if (oper == "-") { return m_Num1 - m_Num2; } else if (oper == "*") { return m_Num1 * m_Num2; } //如果扩展新的功能,需要修改源码 //在真实的开发中,提倡开闭原则 //开闭原则:对扩展进行开放,对修改进行关闭 } int m_Num1; int m_Num2; }; void test01() { //创建计算器对象 Calculator c; c.m_Num1 = 10; c.m_Num2 = 10; cout << c.m_Num1 << "+" << c.m_Num2 << "=" << c.getResult("+") << endl; } //利用多态实现计算器 //实现计算器抽象类 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* abc = new AddCalculator; abc->m_Num1 = 10; abc->m_Num2 = 100; cout << abc->m_Num1 << " + " << abc->m_Num2 << " = " << abc->getResult() << endl; delete abc; //减法运算 AbstractCalculator* abc = new SubCalculator; abc->m_Num1 = 10; abc->m_Num2 = 100; cout << abc->m_Num1 << " - " << abc->m_Num2 << " = " << abc->getResult() << endl; delete abc; //乘法运算 AbstractCalculator* abc = new MulCalculator; abc->m_Num1 = 10; abc->m_Num2 = 100; cout << abc->m_Num1 << " * " << abc->m_Num2 << " = " << abc->getResult() << endl; delete abc; } int main() { test01(); system("pause"); return 0; }
4.7.3 纯虚函数和抽象类
在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数
纯虚函数语法:virtual 返回值类型 函数名 (函数列表)=0;
抽象类特点:
- 无法实现化对象
- 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
示例:
#include <iostream> using namespace std; //纯虚函数和抽象类 class Base { public: //纯虚函数 //只要有一个纯虚函数,这个类陈伟抽象类 //抽象类特点: //1、无法实例化对象 //2、抽象类的子类必须要重写父类中的纯虚函数,否则也许属于抽象类 virtual void func() = 0; }; class Son :public Base { public: virtual void func() { cout << "func 函数调用!" << endl; }; }; void test01() { //Base b;//报错,纯虚函数不允许实例化对象 //new Base;//报错,堆区也不可以,抽象类无法实例化对象 //Son s;//报错,子类没有重写父类纯虚函数,否则也是纯虚函数无法实例化对象 Son s; Base* base = new Son; base->func(); } int main() { test01(); system("pause"); return 0; }
4.7.4 多态案例二-制作饮品
案例描述:制作饮品的大致流程为:煮水-冲泡-倒入杯中-加入辅料
利用多态技术实现本案例,提供抽象制作饮品基类,提供子类制作咖啡和茶叶
示例:
#include<iostream> using namespace std; //多态案例2 制作饮品 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(); } void test01() { //制作咖啡 doWork(new Coffee); cout << "------------------" << endl; //制作茶 doWork(new Tea); } int main() { test01(); system("pause"); return 0; }
4.7.5 虚析构和纯虚析构
多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码
解决方式:将父类中的析构函数改为虚析构或者纯虚析构
虚析构和纯虚析构共性:
- 可以解决父类指针释放子类对象
- 都需要有具体的函数实现
虚析构和纯虚析构区别:
- 如果是纯虚析构,该类属于抽象类,无法实例化对象
虚析构函数语法:virtual ~类名(){}
纯虚析构语法:virtual ~类名() = 0;
,类名::~类名(){}
示例:
#include <iostream> #include <string> using namespace std; //虚析构和纯虚析构 class Animal { public: Animal() { cout << "Animal构造函数调用" << endl; } //纯虚函数 virtual void speak() = 0; //纯虚析构,需要声明也需要实现 virtual ~Animal() = 0; //{ // cout << "Animal析构函数调用" << endl; //} }; //纯虚析构实现 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() { if (m_Name != NULL) { cout << "Cat析构函数调用" << endl; delete m_Name; m_Name = NULL; } } string* m_Name; }; void test01() { Animal* animal = new Cat("Tom"); animal->speak(); //父类指针在析构时候,不会调用子类中析构函数,导致子类如果有堆区属性,出现内存泄露 delete animal; } int main() { test01(); system("pause"); return 0; }
总结:
- 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
- 如果子类中没有堆区数据,可以不写为虚析构或者纯虚析构
- 拥有纯虚析构函数的类也属于抽象类
4.7.6 多态案例三-电脑组装
案例描述:
电脑主要组成部分为CPU(用于计算),显卡(用于显示),内存条(用于存储),将每个零件封装出抽象类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口。要求测试时组装三台不同的电脑进行工作
示例
#include <iostream> #include <string> 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(); } //提供析构函数,释放3个电脑零件 ~Computer() { //释放cpu 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; //CPU的零件指针 VideoCard* m_vc;//显卡零件指针 Memory* m_mem;//内存条零件指针 }; //具体厂商 //Intel厂商 class IntelCPU :public CPU { public: virtual void calculate() { cout << "Intel 的CPU开始计算了!" << endl; } }; class IntelVideoCard :public VideoCard { public: virtual void display() { cout << "Intel 的显卡开始显示了!" << endl; } }; class IntelMemory :public Memory { public: virtual void storage() { cout << "Intel 的内存条开始存储了!" << endl; } }; //Lenovo厂商 class LenovoCPU :public CPU { public: virtual void calculate() { cout << "Lenovo 的CPU开始计算了!" << endl; } }; class LenovoVideoCard :public VideoCard { public: virtual void display() { cout << "Lenovo 的显卡开始显示了!" << endl; } }; class LenovoMemory :public Memory { public: virtual void storage() { cout << "Lenovo 的内存条开始存储了!" << endl; } }; void test01() { // cout << "第一台电脑开始工作" << endl; //第一台电脑的零件 CPU* intelCpu = new IntelCPU; VideoCard* intelCard = new IntelVideoCard; Memory* intelMem = new IntelMemory; //创建第一台电脑 Computer* computer1 = new Computer(intelCpu, intelCard, intelMem); computer1->work(); delete computer1; // cout << "第二台电脑开始工作" << endl; //第二台电脑的零件 //创建第二台电脑 Computer* computer2= new Computer(new LenovoCPU, new LenovoVideoCard, new LenovoMemory); computer2->work(); delete computer2; cout << "第三台电脑开始工作" << endl; //第三台电脑的零件 //创建第三台电脑 Computer* computer3 = new Computer(new IntelCPU, new LenovoVideoCard, new IntelMemory); computer3->work(); delete computer3; } int main() { test01(); system("pause"); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!