c++程序在执行时,将内存大方向划分为 4个区域
代码区:存放函数体的二进制代码,由操作系统管理。
全局区:存放全局变量和静态变量,常量
栈区:由编译器自动分配释放,存放函数的参数值,局部变量等
堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收
内存四区的意义:
不同区域存放的数据,赋予不同的生命周期,给我们更大的灵活编程
在程序编译后,生成了.exe可执行文件 ,未执行该程序前分为两个区域
代码区:
存放cpu执行的机器指令
代码区是共享的,目的是对于频繁被执行的程序,只需要在内存中有一份即可
代码区是只读的,是为了防止程序意外修改了它的指令
全局区:
全局变量和静态变量存放在此
全局变量还包括常量区,字符串常量和其他常量也存在此
该区域的数据在程序结束后由操作系统释放
局部变量,const修饰的局部变量,局部常量 | 全局变量,静态变量,static关键字,常量(字符串常量,const修饰全局变量(全局常量)) |
---|---|
不在全局区中 | 全局区 |
#include
using namespace std;
//全局变量
int g_a = 10;
int g_b = 20;
//const修饰的全局变量
const int c_g_a = 10;
const int c_g_b = 20;
int main()
{
//普通局部变量
int a = 10;
int b = 20;
cout << "a的局部变量的地址:" << (int)&a << endl;
cout << "b的局部变量的地址:" << (int)&b << endl;
cout << "g_a的局部变量的地址:" << (int)&g_a << endl;
cout << "g_b的局部变量的地址:" << (int)&g_b << endl;
//静态变量 在普通变量前面加 static ,属于静态变量
static int s_a = 10;
static int s_b = 20;
cout << "s_a的静态变量的地址:" << (int)&s_a << endl;
cout << "s_b的静态变量的地址:" << (int)&s_b << endl;
//常量 (字符串常量,const修饰常量)
//字符串常量
cout << "字符串的地址:" << (int)&"hello world"<< endl;
//const修饰的全局常量 const修饰的局部变量
cout << "const修饰的全局变量的地址" << (int)&c_g_a << endl;
cout << "const修饰的全局变量的地址" << (int)&c_g_b << endl;
int c_l_a = 10; //c-const , g-global , l - local
int c_l_b = 20;
cout << "const修饰的局部变量的地址" << (int)&c_l_a << endl;
cout << "const修饰的局部变量的地址" << (int)&c_l_b << endl;
system("pause");
return 0;
}
栈区:
由编译器自动分配释放,存放函数的参数值局部变量等
注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放
#include
using namespace std;
//栈区数据注意事项----不要返回局部变量的地址
int* funs(int b) //形参也在栈区
{
b = 100;
int a = 10; //局部变量 存放在栈区,栈区的数据在函数执行完后自动释放
return &a; //返回局部变量地址
}
int main()
{
//接受func函数的返回值
int*p = funs(1);
cout << *p << endl; //第一次可以打印是由于编译器做了保留
cout << *p << endl; //第二次数据没有保存
system("pause");
return 0;
}
堆区:
由程序员分配释放,若程序员不释放程序结束时由操作系统回收
在C++中主要利用new在堆区开辟内存
#include
using namespace std;
int* func()
{
//利用now关键字,可以将数据开辟到堆区
//指针 本质也是局部变量,放在栈上,指针保存的数据是放在堆区
int* p = new int(10);
return p;
}
int main()
{
//在栈区开辟数据
int* p = func();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
system("pause");
return 0;
}
总结:
堆区数据由程序员管理开辟和释放
堆区数据利用new关键字进行开辟内存
1.3 new操作符
C++中利用new操作符在堆区开辟数据
堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符 delete
语法: new数据类型
利用new创建的数据,会返回该数据对应的类型的指针
#include
using namespace std;
//1.new的基本语法
int* func()
{
//在堆区创建整型模型
//new 返回的是 该数据类型的指针
int* p = new int(10);
return p;
}
void test01()
{
int* p = func();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
//堆区的数据由程序员管理开辟,程序员管理释放
//如果想释放堆区的数据,利用关键字 delete
delete p;
//cout << *p << endl; //内存已经释放,再次访问就是非法操作
}
//2.在堆区利用new开辟数组
void test02()
{
//创建10整型数据的数组,在堆区
int* arr = new int[10]; //10代表有10个元素
for (int i = 0; i < 10; i++)
{
arr[i] = i + 100; //给10个元素赋值 100~109
}
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
//释放数组 加[]
delete[] arr;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
作用:给变量起别名
语法:数据类型 &别名 = 原名
int main()
{
//引用的基本语法
int a = 10;
int& b = a; //引用
cout << a << endl;
cout << b << endl;
b = 200;
cout << a << endl;
cout << b << endl;
system("pause");
return 0;
}
int main()
{
//引用的基本语法
int a = 10;
//int& b ; //引用未初始化 (错误)
int& b = a; //初始化 ,一旦初始化后不能更改
int c = 20;
b = c; //赋值操作
cout << a << endl;
cout << b << endl;
cout << c << endl;
system("pause");
return 0;
}
作用:函数传参时,可以利用 引用 的技术让形参修饰实参
有点:可以简化修改实参
//引用传递
void mySwap03(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
mySwap03(a, b); //引用传递,形参修饰实参
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system("pause");
return 0;
}
总结: 通过引用参数产生的效果同按照地址传递是一样的。引用语法更清楚简单。
**作用:**引用可以做函数返回值存在
注意:不要返回局部变量引用
用法:函数调用作为左值
#include
using namespace std;
//引用 做函数的返回值
//1.不要返回局部变量的引用
int& test01()
{
int a = 10; //局部变量 放在栈区
return a;
}
//2.函数的调用可以作左值
int& test02()
{
static int a = 10; //静态变量 ,全局区上数据在程序结束后释放
return a;
}
int main()
{
//int& ref = test01(); //错误
//cout << "ref = " << ref << endl; //第一次结果正确,是因为编译器做了保存
//cout << "ref = " << ref << endl; //第二次乱码,因为a内存已经释放
int& ref2 = test02(); //test02()是a的引用 ,ref2是a的引用的引用
cout << "ref2 = " << ref2 << endl;
test02() = 100; //2.函数的返回值是引用,函数调用可以作左值
cout << "ref2 = " << ref2 << endl;
system("pause");
return 0;
}
本质:引用的本质在c++内部实现是一个 指针常量
结论: C++推荐用引用技术,因为语法方便,引用本质是指针常量,但是所有的指针操作编译器都帮我们做了
**作用:**常量引用主要用来修饰形参,防止误操作
在函数形参列表中,可以加 const修饰形参 , 防止形参改变实参 (指向地址和值都固定)
#include
using namespace std;
//打印函数
void printValue(const int &val)
{
//val = 100;
cout << val << endl;
}
int main()
{
//常量引用
//加上const 后,编译器将代码修改 int temp = 10; const int &ref = temp;
const int& ref = 10; //引用必须引一块合法的内存空间
//ref = 20; //加入const 变为 (只读)状态,不能修改
//使用场景:用来修饰形参,防止误操作
int a = 10;
printValue(a);
system("pause");
return 0;
}
在C++中,函数的 形参列表 中的形参是可以有默认值的。
语法: 返回值类型 函数名 (参数= 默认值) {}
#include
using namespace std;
//函数默认参数
int func(int a, int b = 20, int c = 30)
{
return a + b + c;
}
//注意1 :如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须右默认值
int func2(int a, int b = 20, int c = 30) //b有默认值,c就必须有(左到右)
{
return a + b + c;
}
//注意2:如果函数声明有默认参数,函数实现就不能有默认参数
int func3(int a = 10, int b = 20); //函数声明
int func3(int a, int b) //声明和实现只有一个有默认参数
{
return a + b;
}
int main()
{
cout << func(10) << endl; //使用默认参数
cout << func(15, 30, 40) << endl; //使用自己输入参数
system("pause");
return 0;
}
C++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置
语法: 返回值类型 函数名(数据类型) {}
在现阶段函数的占位参数存在意义怀大,但是后面的课程中会用到该技术
#include
using namespace std;
//占位函数
void func(int a,int = 10) //int为占位函数(可有默认参数),后面课程使用
{
cout << "this is func" << endl;
}
int main()
{
func(5);
system("pause");
return 0;
}
**作用:**函数名可以相同,提高复用性
函数重载满足条件
注意:函数的返回值不可以作为函数重载的条件
#include
using namespace std;
//函数重载的条件
//1.引用作为重载的条件
void func(int & a)
{
cout << "func(int & a)调用" << endl;
}
void func(const int& a)
{
cout << "func(const int& a)调用" << endl;
}
//函数重载碰到默认参数
void func2(int a,int b)
{
cout << "func2(int a,int b)的调用" << endl;
}
int main()
{
int a = 10;
func(a); //调用func(int&a) 可读可写
func(10); //调用func(const int &a) 只读
func2(1,5);
system("pause");
return 0;
}
C++面向对象的三大特性为:封装、继承、多态
例如:
人可以作为对象,属性有姓名、年龄、身高、体重…行为有走、跑、跳、吃饭、唱歌…
车也可以作为对象,属性有轮胎、方向盘、车灯…行为有载人、 放音乐、放空调…
具有相同性质的 对象,我们可以抽象称为 类,人属于人类,车属于车类
封装的意义:
封装意义一:
在设计类的时候,属性和行为写在一起,表现事物
语法: class 类名 {访问权限: 属性/ 行为};
#include
using namespace std;
const double PI = 3.14159; //圆周率
//设计一个圆类,求圆的周长
class circle
{
//访问权限
public:
//属性(变量)
int m_r;
//行为(函数)
double calculateZC()
{
return 2 * PI * m_r;
}
};
int main()
{
//通过 圆类 创建具体对象 实例化对象
circle cl;
//给圆对象 的属性进行赋值
cl.m_r = 10;
cout << "圆的周长:" << cl.calculateZC() << endl;
system("pause");
return 0;
}
设计一个学生类,属性有姓名和学号,可以显示学生的姓名和学号
#include
using namespace std;
#include
//设计学生类
class Student
{
public: //公共权限
//属性
string m_Name;
int m_ID;
//行为
//显示姓名和学号的函数
void showStudent()
{
cout << "学生的姓名:" << m_Name << " " << "学生的学号:" << m_ID << endl;
}
//给姓名赋值
void setName(string name)
{
m_Name = name;
}
//给学号赋值
void setID(int id)
{
m_ID = id;
}
};
int main()
{
Student stu;
stu.m_Name = "张三";
stu.m_ID = 10;
stu.showStudent();
Student s2;
s2.setName("李四");
s2.setID(20);
s2.showStudent();
system("pause");
return 0;
}
类中的属性和行为 我们统称为 成员
封装意义二:
类在设计的时候,可以把属性和行为放在不同的权限下,加以控制
访问权限有三种
#include
#include
using namespace std;
//公共权限 public 成员 类内可以访问 类外可以访问
//保护权限 protected 成员 类内可以访问 类外不可以访问 (子类可以访问父类 保护内容)
//私有权限 private 成员 类内可以访问 类外不可以访问 (子类不可以访问父类 私有内容)
class Person
{
public: //公共权限
string m_Name;
protected:
string m_Car;
private:
string m_Password;
public:
void func()
{
m_Name = "张三";
m_Car = "奔驰";
m_Password = "666";
}
};
int main()
{
//实例化对象
Person p;
p.m_Name = "张三";
// p.m_Car = "宝马"; m_Car 是保护权限 在类外无法访问
// p.m_Psaaword = "777"; m_Password 是私有权限 在类外无法访问
system("pause");
return 0;
}
struct 和 class 唯一区别:默认访问的权限不同
区别:
#include
using namespace std;
class C1
{
int m_A; //默认权限 private
};
struct C2
{
int m_A; //默认权限 public
};
int main()
{
C1 c1;
//c1.m_A = 15; class默认 私有权限不可访问
C2 b;
b.m_A = 10; //struct 默认 公共可以访问
cout << b.m_A << endl;
system("pause");
return 0;
}
个人理解:
声明结构体的方式和声明类的方式大致相同,区别如下:尽管结构体可以包含函数,但是很少这样使用。 通常情况下结构体声明只会声明变量,结构体是为了兼容c语言存在的,尽量使用class
**优点1:**将所有成员属性设为私有,可以自己控制读写权限
**优点2:**对于写权限,我们可以检测数据的有效性
#include
using namespace std;
#include
//设置人类
class Person
{
public:
//设置姓名
void setname(string name)
{
m_name = name;
}
//获取姓名
string getname()
{
return m_name;
}
//获取年龄 改为 可读可写状态(范围0~100)
int getage()
{
return m_age;
}
//设置年龄
void setage(int age)
{
if (age<0||age>100)
{
m_age = 0;
cout << "您输入年龄有误" << endl;
return;
}
else
{
m_age = age;
}
}
//设置爱人
void getlover(string lover)
{
m_lover = lover;
}
private:
string m_name; //姓名 可读可写
int m_age; //年龄 只读 后改可读可写
string m_lover; //爱人 只写
};
int main()
{
Person p;
p.setname("小谭");
cout << p.getname() << endl;
p.setage(30);
cout << p.getage() << endl;
p.getlover("周杰伦");
//cout << "最喜欢的明星:" << p.getlover("周杰伦") << endl; 只能写入,不能外部访问
system("pause");
return 0;
}
**练习案例:**设计一个圆类,和一个点类,计算圆和点的位置关系
封装头文件 (去除函数的实现)
# pragma once //防止头文件重复包含
#include
using namespace std;
class Point
{
private:
int m_X;
int m_Y;
public:
//设置x,y坐标
void setXY(int x, int y);
//获取x,y坐标
int getX();
int getY();
};
#pragma once
#include
#include"point.h" //引用point 头文件
using namespace std;
//圆类
class Circle
{
private:
int m_R; //半径
Point m_Center; //圆心
public:
//设置半径
void setR(int r);
//获取半径
int getR();
//设置圆心
void setCenter(Point center);
//获取圆心
Point getCenter();
};
封装源文件
#include"point.h"
//设置x,y坐标
void Point:: setXY(int x, int y) //添加 Point::
{
m_X = x;
m_Y = y;
}
//获取x,y坐标
int Point ::getX()
{
return m_X;
}
int Point::getY()
{
return m_Y;
}
#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;
}
主代码区
#include
#include"circle.h" //引用封装的的 圆头文件
#include"point.h" //引用封装的的 点头文件
using namespace std;
//判断点和圆关系
void isInCircle(Circle &c,Point &p)
{
//计算两点之间距离平方
int distance = (c.getCenter().getX() - p.getX()) ^ 2 + (c.getCenter().getY() - p.getY()) ^ 2;
//计算半径的平方
int Rdistance= c.getR() * c.getR();
//判断关系
if (distance == Rdistance)
{
cout << "点在圆上" << endl;
}
else if (distance < Rdistance)
{
cout << "点在圆外" << endl;
}
else if (distance > Rdistance)
{
cout << "点在圆内" << endl;
}
}
int main()
{
//创建圆
Circle c;
//创建点
Point p;
Point cp; //圆心 在一个类中,让另一个类作为本来的成员
//设置点的坐标 ,圆心的坐标 , 圆的半径
p.setXY(5, 12);
cp.setXY(16,6);
c.setR(5);
c.setCenter(cp);
//调用判断函数
isInCircle(c, p);
system("pause");
return 0;
}
●C++中的面向对象来源于生活,每个对象也都会有初始设置以及对象销毁前的清理数据的设置。
对象的初始化和清理也是两个非常重要的安全问题
C++利用了构造函数和析构函数解决.上述问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。对象的初始化和清理工作是编译器强制要我们做的事情,因此如果我们不提供构造和析构,编译器会提供编译器提供的构造函数和析构函数是空实现。
●**构造函数:**主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。
●**析构函数:**主要作用在于对象销毁前系统自动调用,执行一 些清理工作。
构造函数的语法: 类名(){}
析构函数的语法:~类名(){}
#include
using namespace std;
//对象的初始化和清理
//1.构造函数 进行初始化操作
class Person
{
public:
//构造函数没有返回值 ,且不用写viod
//函数名和 类名 相同
//构造函数可以有参数 , 可以重载
//创建对象的时候 , 构造函数会自动调用 , 而且只调用一次
Person()
{
cout << "构造函数的调用" << endl;
}
//析构函数 进行清理操作
//没有返回值 不写 void
//函数名和类名 不同 名称前加(~)
//析构函数不可以有参数 不可以重载
//对象在销毁前 会自动调用析构函数 , 而且只调用一次
~Person()
{
cout << "析构函数的调用" << endl;
}
};
void test01()
{
Person p; //栈上的数据 ,函数执行完后释放对象
}
int main()
{
test01();
Person p;
system("pause");
return 0;
}
两种分类方式:
按参数分类: 有参构造 和 无参构造
按类型分类: 普通构造 和 拷贝构造
三种调用方式
括号法
显示法
隐式转换法
#include
using namespace std;
// 参数 (无参构造) (有参构造)
// 类型 (普通构造) (拷贝构造)
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;
}
int age;
};
//调用
void test01()
{
//1.括号法
Person p1; //默认构造函数调用
Person p2(10); //有参构造函数调用
Person p3(p2); //拷贝构造函数调用
//cout << "p2的年龄为:" << p2.age<
c++中拷贝构造函数调用时机通常有三种情况
#include
using namespace std;
// 拷贝构造函数调用时机
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;
}
默认情况下,c++编译器至少给一个类添加3个函数
构造函数调用规则如下:
#include
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;
}
int m_Age;
};
//void test01()
//{
// Person p;
// p.m_Age = 18;
// Person p2(p);
//
// cout << "p2 的年龄为:" <
深拷贝是面试经典问题 ,也是常见坑
**浅拷贝:**简单的赋值拷贝操作
**深拷贝:**在堆区重新申请空间,进行拷贝操作
#include
using namespace std;
//深拷贝和浅拷贝
class Person
{
public:
Person()
{
cout << "Person 默认构造函数调用" << endl;
}
Person(int age,int height ) //有参构造
{
m_Age = age;
m_Height = new int(height); //新开辟堆区数据 堆区数据程序员释放
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);
}
~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 的年龄为:" <
**总结:**如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题
**作用:**C++提供了初始化列表语法,用来初始化属性
**语法:**构造函数();属性1(值1) , 属性2(值2)…{}
#include
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(30,20,10);
cout << "m_A = " << p.m_A << endl;
cout << "m_B = " << p.m_B << endl;
cout << "m_C = " << p.m_C << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
C++类中的成员可以是另一个类的对象,我们称该成员 为 对象成员
例如:
class A{}
class B
{
A a;
}
B类中有对象A作为成员 , A为对象成员
那么当创建B对象时,A和B的构造和析构的顺序 那个先?
先A 析构函数顺序和构造相反
#include
using namespace std;
#include
class Phone
{
public:
Phone(string name)
{
cout << "Phone 的构造函数调用" << endl;
m_PName = name;
}
~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;
}
//姓名
string m_Name;
//手机
Phone m_Phone;
~Person()
{
cout << "Person 的析构函数调用" << endl;
}
};
//当其他类对象作为本类成员 , 构造时候先构造类对象 ,再构造自身
void test01()
{
Person p("小谭","小米");
cout <
静态成员就是在成员变量和成员函数前加上关键字 static ,成为静态成员
静态成员分为:
静态成员变量
静态成员函数
例1 :静态成员变量
#include
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;
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;
}
例二:静态成员函数
#include
using namespace std;
//静态成员函数
//所有对象共享同一个函数
//静态成员函数只能访问静态成员变量
class Person
{
public:
//静态成员函数
static void func()
{
//m_B = 10; 静态成员函数不可以访问 非静态成员变量
m_A = 100; //静态成员函数可以访问 静态成员变量
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 = 0;
void test01()
{
//1.通过对象访问
Person p;
p.func();
//2.通过类名访问
Person::func();
// Person::func2(); 类外访问不到私有静态成员函数
}
int main()
{
test01();
system("pause");
return 0;
}
在C++中,类内的 成员变量 和 成员函数 分开储存
只有非静态成员变量才属于类的对象上
#include
using namespace std;
//成员变量 和 成员函数 分开存储
class Person
{
int m_A; //非静态成员变量 属于类的对象上
static int m_B; //静态成员变量 不属于类的对象上
void func() {} //非静态成员函数 不属于类的对象上
static void func2() //静态成员函数 不属于类的对象上
{}
};
int Person::m_B;
void test01()
{
Person p;
//空对象占用的内存空间为: 1
//编译器会给每一个空对象也分配一个字节空间 , 是为了区分空对象占内存的位置
cout << "sizeof p =" << sizeof(p) << endl;
}
void test02()
{
Person p;
cout << "sizeof p =" << sizeof(p) << endl; //4个字节
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
每一个非静态成员函数只会诞生-份函数实例,也就是说多个同类型的对象会共用一块代码
那么问题是:这-块代码是如何区分那个对象调用自己的呢?
C++通过提供特殊的对象指针,this指针, 解决上述问题。this指针指向被调用的成员函数所属的对象
this指针是隐含每一个非静态成员函数内的一-种指针
this指针不需要定义,直接使用即可
this指针的用途:
●当形参和成员变量同名时,可用this指针来区分
●在类的非静态成员函数中返回对象本身,可使用return *this
#include
using namespace std;
class Person
{
public:
Person(int age)
{
this-> age = age;
}
int age;
Person & PersonAddAge(Person &p)
{
this->age += p.age;
//this 指向p2的指针 , 而*this指向的就是p2这个对象本体
return *this;
}
};
//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);
cout << "p2的年龄为:" << p2.age << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
#include
using namespace std;
//空指针调用成员函数
class Person
{
public:
void showClassName()
{
cout << "this is Person class" << endl;
}
void showPersonAge()
{
if (this == NULL)
{
return;
}
//报错原因是因为传入的指针是为 NULL
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;
}
常函数:
常对象:
#include
using namespace std;
//常函数
class Person
{
public:
//this 指针的本质 是指针常量 指针的指向是不可以修改的
// const Person * const this ;
//在成员函数后面加const ,修饰的是this指向 ,让指针指向的值也不可以修改
void showPerson() const //函数体后 添加 const 后不能修饰
{
//this->m_A = 100;
//this = NULL; //this 指针是不可以修改指针的指向的
this->m_B = 100;
}
void func()
{
}
int m_A;
mutable int m_B; //特殊变量 ,即使在常函数中,也可以修改这个值 加上关键字 mutable
};
void test01()
{
Person p;
p.showPerson();
}
//常对象
void test02()
{
const Person p; //在对象前加上 const
//p.m_A = 100;
p.m_B = 100; //m_B是特殊值,在常对象下也可以修改
//常对象只能调用常函数
p.showPerson();
//p.func(); //常对象不能调用普通函数 , 因为普通成员函数可以修改属性
}
int main()
{
system("pause");
return 0;
}
生活中你的家有客厅(Public),有你的卧室(Private) ,但是呢,你也可以允许你的好闺蜜好基友进去。
在程序里,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
友元的目的就是让一个函数或者类访问另一个类中私有成员
友元的关键字为friend
友元的三种实现
#include
using namespace std;
#include
class Building
{
//设置全局变量 可以访问Building中私有成员
friend void goodGay(Building* building);
public:
Building()
{
m_BedRoom = "卧室";
m_SittingRoom = "客厅";
}
public:
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
};
//全局函数
void goodGay(Building *building)
{
cout << "好朋友全局函数 正在访问:" << building->m_SittingRoom << endl;
//private 私有权限不能类外访问 ,但是可以通过友元 friend获取
cout << "好朋友全局函数 正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
Building building;
goodGay(&building);
}
int main()
{
test01();
system("pause");
return 0;
}
类做友元
#include
using namespace std;
#include
//类做友元
class Building; //声明
class GoodGay
{
public:
GoodGay(); //构造函数初始化
void vist(); //参观函数 访问Building中的属性
Building* building;
};
class Building
{
//GoodGay类是本来的好朋友 ,可以访问本类中私有成员
friend class GoodGay;
public:
Building();
public:
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
};
//类外写成员函数
Building::Building() //Building::表示 Building 作用域下的构造函数
{
m_BedRoom = "卧室";
m_SittingRoom = "客厅";
}
GoodGay::GoodGay()
{
//创建建筑物对象
building = new Building; //堆区创建对象
}
void GoodGay::vist()
{
cout << "好基友正在访问:" << building->m_SittingRoom << endl;
cout << "好基友正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
GoodGay g;
g.vist();
}
int main()
{
test01();
system("pause");
return 0;
}
成员函数做友元
#include
using namespace std;
#include
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 = "客厅";
m_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 << "visit2 函数正在访问: " << building->m_BedRoom << endl;
}
void test01()
{
GoodGay gg;
gg.visit();
gg.visit2();
}
int main() {
test01();
system("pause");
return 0;
}
运算符重载概念:对已有的运算符重新进行定义,赋予其另外一种功能 ,以适应不同的数据类型
**作用:**实现两个自定义数据类型相加的运算
#include
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_B + 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;
}
//3.运算符 ,函数重载
Person operator+(Person& p, int num)
{
Person temp;
temp.m_A = p.m_A + num;
temp.m_B = p.m_B + num;
return temp;
}
void test01()
{
Person p1;
p1.m_A = 10;
p1.m_B = 20;
Person p2;
p2.m_A = 30;
p2.m_B = 40;
//成员函数重载 本质: Person p3 = p1.operator+(p2);
//全局函数重载 本质: Person p3 = operator+(p1,p2);
Person p3 = p1 + p2;
cout << "p3.m_A = " << p3.m_A << " p3.m_B = " << p3.m_B << endl;
//运算符重载 也可以发生函数重载
Person p4 = p3 + 10;
cout << "p4.m_A = " << p4.m_A << " p4.m_B = " << p4.m_B << endl;
}
**总结:**对于内置的数据类型的表达式的运算符是不可能改变的
不要滥用运算符重载
作用: 可以输入自定义数据类型
#include
using namespace std;
//左移运算符重载
class Person
{
public:
int m_A;
int m_B;
};
//只能利用全局函数重载左移运算符
ostream & operator<<(ostream & cout,Person p) //本质 operator<<(cout,p) 简化 cout<
总结:重载左移运算符配合友元可是实现输出自定义数据类型
作用: 通过重载递增运算符,实现自己的整型数据
#include
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)
{
//先 记录当时返回结果
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;
}
void test02()
{
MyInteger myint;
cout << myint++ << endl;
cout << myint << endl;
}
int main()
{
test01();
cout << endl;
test02();
system("pause");
return 0;
}
前置递增 返回 引用
后置递增 返回 值
c++编译器至少给一个类添加4个函数
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题
#include
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;
}
}
int * 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;
}
};
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;
}
作用: 重载关系运算符 ,可以让两个自定义类型对象进行对比操作
#include
using namespace std;
#include
//关系运算符重载
class Person
{
public:
Person(string name,int age)
{
m_Age = age;
m_Name = name;
}
//重载 == 号
bool operator==(Person& p)
{
if (this->m_Age == p.m_Age && this->m_Name == p.m_Name)
{
return true;
}
return false;
}
//重载 != 号
bool operator !=(Person& p)
{
if (this->m_Age == p.m_Age && this->m_Name == p.m_Name)
{
return false;
}
return true;
}
string m_Name;
int m_Age;
};
void test01()
{
Person p1("小谭",18);
Person p2("小谭", 28);
//重载 == 时
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;
}
#include
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(150, 230);
cout << "ret = " << ret << endl;
//匿名函数对象
cout << MyAdd()(50, 50) << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
继承是面向对象三大特性之一
我们发现,定义这些类时,下级别的成员除了拥有上一级的共性,还有自己的特性
这个时候我们就可以考虑利用继承的技术,减少重复代码
例如我们看到的很多网站中,都有公共的头部,公共的底部,甚至公共的左侧列表,只有中心内容不同
接下来我们分别利用普通写法 和 继承写法来实现网页中的内容 ,看一下继承存在的意义以及好处
普通实现:
#include
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;
}
};
//Python 页面
class Python
{
public:
void header()
{
cout << "首页,公开课,登录,注册。。。(公共头部)" << endl;
}
void footer()
{
cout << "帮组中心,交流合作,站内地图....(公共底部)" << endl;
}
void left()
{
cout << "Python,C++......(公共分类列表)" << endl;
}
void content()
{
cout << "Python学科视频" << 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;
}
};
void test01()
{
cout << "Java下载视频页面如下:" << endl;
Java java;
java.content();
java.footer();
java.left();
java.content();
cout <<"----------------------"<< endl;
cout << "Python下载视频页面如下:" << endl;
Python py;
py.content();
py.footer();
py.left();
py.content();
cout << "----------------------" << endl;
cout << "C++下载视频页面如下:" << endl;
CPP cpp;
cpp.content();
cpp.footer();
cpp.left();
cpp.content();
}
int main()
{
test01();
system("pause");
return 0;
}
使用继承:
继承的好处:减少重复代码
语法:class 子类 : 继承方式 父类
#include
using namespace std;
//继承实现页面
//公共页面类
class BasePage
{
public:
void header()
{
cout << "首页,公开课,登录,注册。。。(公共头部)" << endl;
}
void footer()
{
cout << "帮组中心,交流合作,站内地图....(公共底部)" << endl;
}
void left()
{
cout << "Java,Python,C++......(公共分类列表)" << endl;
}
void content()
{
cout << "Java学科视频" << endl;
}
};
//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 java;
java.content();
java.footer();
java.left();
java.content();
cout << "----------------------" << endl;
cout << "Python下载视频页面如下:" << endl;
Python py;
py.content();
py.footer();
py.left();
py.content();
cout << "----------------------" << endl;
cout << "C++下载视频页面如下:" << endl;
CPP cpp;
cpp.content();
cpp.footer();
cpp.left();
cpp.content();
}
int main()
{
test01();
system("pause");
return 0;
}
class A: public B;
A 类称为子类 , 或者派生类
B 类称为父类 ,或者基类
派生类中的成员,包含两大部分:
一类是从基类继承过来的 , 一类是自己增加的成员
从基类继承过来的表现其共性 , 而新增的成员体现了其个性
继承的语法: class 子类 : 继承方式 父类
继承方式有三种:
#include
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 = 20; //父类中的保护权限成员 , 到了子类中依然是保护权限
//m_C = 30; 父类中的私有权限成员 , 到了子类中不能访问
}
};
void test01()
{
Son1 s1;
s1.m_A = 20;
//s1.m_B = 20; 到Son1 中m_B是保护权限 , 类外访问不到
}
//保护继承
class Son2 : protected Base1
{
public:
void func()
{
m_A = 10; //父类中公共成员 , 到子类中变为保护成员
m_B = 20; //父类中保护成员 , 到子类中变为保护成员
//m_C = 30; 父类中私有成员 子类访问不到
}
};
void test02()
{
Son2 s2;
//s2.m_A = 10; 在Son2 中 m_A变为了保护权限 , 因此类外访问不到
//s2.m_B = 20; 在Son2 中 m_B保护权限 , 不可以访问
//s2.m_C = 30;
}
//私友继承
class Son3 :private Base1
{
public:
void func()
{
m_A = 10; //父类中公共成员 到子类中变为 私有成员
m_B = 20; //父类中保护成员 到子类中变为 私友成员
//m_C = 30; 父类中私有成员 ,子类访问不到
}
};
//创建孙子类
class GrandSon : public Son3
{
public:
void func()
{
/*m_A = 10;
m_B = 10; 到了Son3在中 都变为私有 , 及时是儿子, 也访问不到
m_C = 10;*/
}
};
void test03()
{
Son3 s3;
//s3.m_A = 20; 到Son3中 变为私有成员 类外访问不到
//s3.m_B = 20; 到Son3中 变为私有成员 类外访问不到
//s3.m_C = 20;
}
int main()
{
system("pause");
return 0;
}
**问题:**从父类继承过来的成员 , 那些属于子类对象
#include
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()
{
//父类中所有非静态成员属性都会被子类继承下去 16 字节
//父类中私有成员属性 是被编译器给隐藏了, 因此是访问不到 , 但是确实被继承下去了
cout << "sizeof Son =" << sizeof(Son) << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
利用开发人员命令提示工具查看对象模型
子类继承父类后 , 当创建子类对象 , 也会调用父类的构造函数
**问题:**父类和子类的 构造 和 析构 顺序是谁先谁后?
父类构造 子类构造 子类析构 父类析构
#include
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();
system("pause");
return 0;
}
**问题:**当子类与父类出现同名的成员 , 如何通过子类对象 , 访问到子类或父类中同名的数据?
#include
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; //s.Base::m_A 在父类作用域下访问
}
//同名成员函数 测试
void test02()
{
Son s;
s.func(); //调用子类中的同名func()函数
s.Base::func(); //调用父类中的同名func()函数
//如果子类中出现和父类同名出现的成员函数,子类的同名成员函数会隐藏掉父类中所有同名成员函数(父类中重载)
//如果想访问到父类中被隐藏的同名成员函数 , 需要加作用域
s.Base::func(10);
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
总结:
问题: 继承中同名的静态成员在子类对象上如何进行访问?
静态成员和非静态成员出现同名,处理方式一致
#include
using namespace std;
//继承同名静态成员处理方式
class Base
{
public:
static int m_A;
void func()
{
cout << "Base类下同名func()函数的调用" << endl;
}
};
int Base::m_A = 200;
class Son :public Base
{
public:
static int m_A;
void func()
{
cout << "Son类下同名func()函数的调用" << endl;
}
};
int Son::m_A = 100;
//同名的静态成员属性
void test01()
{
//通过对象访问
cout << "通过对象访问" << endl;
Son s;
cout <<"Son m_A = "<< s.m_A << endl; //直接访问
cout <<"Base m_A = "<< s.Base::m_A << endl; //通过添加作用域 访问父类同名成员属性
//通过类名访问
cout << "通过类名访问" << endl;
cout << "Son m_A = " << Son::m_A << endl;
//第一个::代表通过类名方式访问 第二个::代表访问父类作用域下
cout << "Base m_A = " << Son::Base::m_A << endl;
//同名的静态成员函数
s.func(); // Son::func();
s.Base::func(); //Son::Base::func();
}
int main()
{
test01();
system("pause");
return 0;
}
C++允许一个类继承多个类
语法: class 子类 :继承方式 父类 , 继承方式 父类 …
多继承可能会引发父类中有同名成员出现,需要加作用域区分
C++实际开发中不建议用多继承
#include
using namespace std;
//多继承语法
class Base1
{
public:
Base1()
{
m_A = 100;
}
int m_A;
};
class Base2
{
public:
Base2()
{
m_A = 200;
}
int m_A;
};
//子类 需要继承Base1 和 Base2
class Son :public Base1, public Base2
{
public:
Son()
{
m_C = 150;
m_D = 250;
}
int m_C;
int m_D;
};
void test01()
{
Son s;
cout << "sizeof s = " << 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;
}
总结: 多继承中,如果父类中出现了同名情况,子类使用时候要加作用域区分
菱形继承概念:
两个派生类继承同一个基类
又有某个类同时继承两个派生类
这种继承被称为菱形继承 , 或者钻石继承
菱形继承问题:
1.羊继承了动物的数据,驼同样继承了动物的数据,当草泥马使用数据时,就会产生二义性。
2.草泥马继承自动物的数据继承了两份,其实我们应该清楚,这份数据我们只需要一份就可以。
#include
using namespace std;
//菱形继承
//动物类
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 = 18;
st.Tuo::m_Age = 28;
//当菱形继承 , 两个父类拥有相同数据,需要加以作用域区分。
cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;
cout << "st.Tuo::m_Age = " << st.Tuo::m_Age << endl;
cout << "sm_Age = " << st.m_Age << endl;
//这份数据我们只需要有一份, 菱形继承导致数据有两份 ,资源浪费
}
int main()
{
test01();
system("pause");
return 0;
}
vfptr 虚函数(表)指针 vftable 虚函数表
v-- ------virtual v-- ------virtual
f----------funotion f----------funotion
ptr------pointer table-----table
多态是C++面向对象三大特性之一
多态分为两类:
静态多态 和 动态多态区别:
#include
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 & animal = cat;
{
animal.speak();
}
void test01()
{
Cat cat;
doSpeak(cat);
Dog dog;
doSpeak(dog);
}
int main()
{
test01();
system("pause");
return 0;
}
总结:
多态满足条件:
多态的使用条件:
**重写:**函数返回值类型 函数名 参数列表 完全一致称为重写
案例描述:
分别利用普通写法和多态技术 , 设计实现两个操作数进行运算的计算器类
多态的优点:
#include
using namespace std;
#include
//分别利用普通写法 和 多态技术 实现计算器
//普通写法
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;
};
//利用多态实现计算器
//实现计算器抽象类
class AbstractCalculator
{
public:
virtual int getResult()
{
return 0;
}
int m_Num1;
int m_Num2;
};
//加法计算器类
class AddCalculator :public AbstractCalculator
{
public:
virtual 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 = 20;
abc->m_Num2 = 30;
cout << abc->m_Num1 << "+" << abc->m_Num2 << " = " << abc->getResult() << endl;
//new 在堆区 用完记得销毁
delete abc;
//减法运算
abc = new SubCalculator;
abc->m_Num1 = 20;
abc->m_Num2 = 30;
cout << abc->m_Num1 << "-" << abc->m_Num2 << " = " << abc->getResult() << endl;
delete abc;
//乘法运算
abc = new MulCalculator;
abc->m_Num1 = 20;
abc->m_Num2 = 30;
cout << abc->m_Num1 << "*" << abc->m_Num2 << " = " << abc->getResult() << endl;
delete abc;
}
void test01()
{
//创建计算器对象
Calculator c;
c.m_Num1 = 10;
c.m_Num2 = 10;
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;
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}
4.7.3 纯虚函数和抽象类
在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数
纯虚函数语法: virtual 返回值类型 函数名 (参数列表)=0;
当类中有了纯虚函数,这个类也称为 抽象类
抽象类特点:
#include
using namespace std;
//纯虚函数和抽象类
class Base
{
public:
//纯虚函数
//只要有一个纯虚函数 , 这个类被称为 抽象类
//抽象类特点:
//1.无法实例化对象
// 2.抽象类子类必须重写父类中的纯虚函数 , 否则也属于抽象类
virtual void func() = 0;
};
class Son :public Base
{
public:
virtual void func()
{
cout << "Son-func()函数调用" << endl;
};
};
void test01()
{
/*Base b; 抽象类是无法实例化对象
new Base;*/
Base* base = new Son;
base->func();
delete base;
Son s; //子类必须重写父类中纯虚函数,否则不能实例化对象
s.func();
}
int main()
{
test01();
system("pause");
return 0;
}
案例描述:
制作饮品的大致流程为:煮水 , 冲泡 , 倒入杯中 , 加入辅料
冲咖啡:煮水 , 冲泡咖啡 , 倒入杯中 , 加糖和牛奶
冲茶叶:煮水 , 冲泡茶叶 , 倒入杯中 , 加柠檬
利用多态技术实现本案例 , 提供抽象制作饮品基类 , 提供子类制作咖啡和 茶叶
#include
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) // AbstractDrinking* abs = new Coffee
{
abs->makeDrink();
delete abs; //堆区释放 ,防止内存泄漏
}
void test01()
{
//制作咖啡
dowork(new Coffee);
cout << endl;
//制作茶
dowork(new Tea);
}
int main()
{
test01();
system("pause");
return 0;
}
多态使用时,如果子类中有属性开辟到堆区 , 那么父类指针在释放时无法调用到子类的析构代码
解决方式:将父类中的析构函数改为 虚析构 或者 纯虚析构
虚析构和纯虚析构共性:
虚析构和纯虚析构区别:
虚析构语法:
virtual ~类名(){}
纯虚析构语法:
virtual ~类名() {} =0 ;
类名::~类名(){}
#include
using namespace std;
#include
//虚析构和纯虚析构
class Animal
{
public:
Animal()
{
cout << "Animal的构造函数调用" << endl;
}
//利用虚析构 可以解决 父类指针释放子类对象时不干净的问题
/*virtual ~Animal()
{
cout << "Animal的析构函数调用" << endl;
}*/
//纯虚析构
//有了纯虚析构之后 , 这个类也属于抽象类 , 无法实例化对象
virtual ~Animal() = 0;
virtual void speak() = 0;
};
Animal:: ~Animal()
{
cout << "Animal的纯析构函数调用" << endl;
};
class Cat :public Animal
{
public:
Cat(string name)
{
cout << "Cat构造函数调用" << endl;
m_Name = new string(name);
}
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;
}
总结:
1.虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
2.如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
3.拥有纯虚析构函数的类也属于抽象类
案例描述:
电脑主要组成部件为CPU (用于计算),显卡(用于显示),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂 商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
#include
using namespace std;
//抽象不同零件类
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* men)
{
m_cpu = cpu;
m_vc = vc;
m_mem = men;
}
//提供工作的函数
void work()
{
//让零件工作起来 , 调用接头
m_cpu->calculate();
m_mem->storage();
m_vc->display();
}
//提供析构函数 释放3个电脑零件
~Computer()
{
//释放堆区零件
if (m_cpu != NULL)
{
delete m_cpu;
m_cpu = NULL;
}
if (m_mem != NULL)
{
delete m_mem;
m_mem = NULL;
}
if (m_vc != NULL)
{
delete m_vc;
m_vc = NULL;
}
}
private:
CPU* m_cpu;
VideoCard* m_vc;
Memory * m_mem;
};
//具体厂商
class InterCPU :public CPU
{
public:
virtual void calculate()
{
cout << "Inter i9 10900k 开始计算了!" << endl;
}
};
class InterVideo :public VideoCard
{
public:
virtual void display()
{
cout << "RTX 3090 开始显示了!" << endl;
}
};
class InterMemory :public Memory
{
public:
virtual void storage()
{
cout << "sn750 开始储存了!" << endl;
}
};
//Lenovo厂商
class LenovoCPU :public CPU
{
public:
virtual void calculate()
{
cout << " i7 10700k 开始计算了!" << endl;
}
};
class LenovoVideo :public VideoCard
{
public:
virtual void display()
{
cout << "RTX 3060Ti 开始显示了!" << endl;
}
};
class LenovoMemory :public Memory
{
public:
virtual void storage()
{
cout << "sn550 开始储存了!" << endl;
}
};
void test01()
{
//第一台电脑零件
CPU* interCpu = new InterCPU;
VideoCard* interCard = new InterVideo;
Memory* interMen = new InterMemory;
//创建第一台电脑
Computer* computer1 = new Computer(interCpu, interCard, interMen);
computer1->work();
delete computer1;
cout << endl;
//第二台电脑
cout << "第二台电脑:" << endl;
Computer* computer2 = new Computer(new LenovoCPU, new LenovoVideo, new LenovoMemory);
computer2->work();
delete computer2;
}
int main()
{
test01();
system("pause");
return 0;
}
程序运行时产生的数据都属于临时数据 ,程序一旦运行结束都会被释放
通过文件可以将数据持久化
C++中对文件操作需要包含头文件
文件类型分为两种:
操作文件的三大类:
写文件步骤如下:
1.包含头文件
#include
2.创建流对象
oFstream ofs;
3.打开文件
ofs.open(“文件路径” ,打开方式);
4.写数据
ofs << “写入的数据”;
5.关闭文件
ofs.close();
文件打开方式:
打开方式 | 解释 |
---|---|
ios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 初始位置:文件尾. |
ios::app | 追加方式写文件 |
ios::trunc | 如果文件存在先删除,再创建 |
ios::binary | 二进制方式 |
**注意:**文件打开方式可以配合使用,利用|操作符
**例如:**用二进制方式写文件 ios::binary | ios::out
#include
using namespace std;
#include //头文件包含
//文本文件 写文件
void test01()
{
//1.包含头文件 fstream
//2.创建流对象
ofstream ofs;
//3.指定打开方式
ofs.open("test.txt", ios::out);
//4.写入内容
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:28" << endl;
//5.关闭文件
ofs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
读文件和写文件步骤相识 , 但是读取方式相对比较多
读文件步骤如下:
1.包含头文件
#include
2.创建流对象
ifstream ifs;
3.打开文件并判断文件是否打开成功
ifs.open(“文件路径” ,打开方式);
4.读数据
四种方式读取
5.关闭文件
ifs.close();
#include
using namespace std;
#include //头文件包含
#include
//文本文件 读文件
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 }; //字符数组初始化为0
while (ifs >> buf)
{
cout << buf << endl; //将文件数据读入 buf字符数组
}
//读取方式二
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();
system("pause");
return 0;
}
总结:
●读文件可以利用ifstream ,或者fstream类
●利用is_ open函数可以判断文件是否打开成功
●close关闭文件
以二进制的方式对文件进行读写操作
打开方式要指定为 ios::binary
二进制方式写文件主要利用流对象调用成员函数write
函数原型:ostream & write(const char * buffer , int len);
解释参数:字符指针buffer指向内存中一段储存空间 , len 是读写的字节数
#include
using namespace std;
#include //头文件包含
#include
//二进制文件 写文件
class Person
{
public:
char m_Name[64]; //姓名
int m_Age; //年龄
};
void test01()
{
//1.包含头文件 fstream
//2.创建流对象
ofstream ofs;
//3.打开文件
ofs.open("Person.txt", ios::in | ios::binary);
//4.写文件
Person p = { "小林",23 };
ofs.write((const char*)&p,sizeof(Person));
//5.关闭文件
ofs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
二进制方式读文件主要利用流对象调用成员函数read
函数原型: istream& read(char *buffer,int len);
参数解释:字符指针buffer指向内存中- -段存储空间。len是读写的字节数
#include
using namespace std;
#include
//二进制文件 读文件
class Person
{
public:
char m_Name[64]; //姓名
int m_Age; //年龄
};
void test01()
{
//1.包含头文件 fstream
//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();
system("pause");
return 0;
}
●文件输入流对象可以通过read函数,以二进制方式读数据