C++程序在执行时,将内存大方向划分为4个区域
内存四区意义
不同区域存放的数据,赋予不同的生命周期,给我们更大的灵活编程
在代码编译后,生成了exe可执行程序,未执行该程序前分别为两个区域
代码区:
存放CPU执行的机器指令
代码区是共享的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可
代码区是只读的,使其只读的原因是防止程序意外地修改了它的指令
全局区:
全局变量和静态变量存放在此
全局区还包含了常量区,字符串常量和其他常量也存放在此
该区域的数据在程序结束后由操作系统释放
总结:
栈区:
由编译器自动分配释放,存放函数的参数值,局部变量等
注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放
#include
using namespace std;
// 栈区数据注意事项 --不要返回局部变量的地址
// 栈区数据由编译器管理开辟和释放
int* func(int b) // 形参数据也会放在栈区
{
b = 100;
int a = 10; // 局部变量 存放在栈区,栈区的数据在函数执行完后自动释放
return &a; // 返回局部变量的地址
}
int main()
{
int *p = func(1);
cout << *p << endl; // 第一次可以打印正确的数字,是因为编译器做了一次保留
cout << *p << endl; // 第二次这个数据就不再保留了
system("pause");
return 0;
}
堆区:
由程序员分配释放,若程序员不释放,程序结束时由操作系统回收
在C++中主要利用new在堆区开辟内存
C++中利用new
操作符在地区开辟数据
堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符delete
语法:new 数据类型
利用new创建的数据,会返回该数据对应的类型的指针
示例:
#include
using namespace std;
int * func1()
{
// 在堆区创建整型数据
// new返回的是 该数据类型的指针
int * p = new int(10);
return p;
}
void test01()
{
int *p = func1();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
//堆区的数据,由程序员开辟,程序员管理释放
//如果想释放堆区的数据,利用关键字 delete
delete p;
}
// 在堆区利用new开辟数组
void test02()
{
// 创建10整型数据的数据,在堆区
int *arr = new int[10]; // 10代表数组有10个元素
for (int i = 0; i < 10; i++)
{
arr[i] = i + 100;
}
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
delete[] arr;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
**作用:**给变量起别名
语法:数据类型 &别名 = 原名
示例:
#include
using namespace std;
int main()
{
// 引用基本语法
// 数据类型 &别名 = 原名
int a = 10;
int &b = a;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
b = 20;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system("pause");
return 0;
}
示例:
#include
using namespace std;
int main()
{
int a = 10;
// 1.引用必须初始化
// int &b; // 错误,必须要初始化
int &b = a;
// 2.引用在初始化后,不可以改变
int c = 20;
b = c; // 赋值操作,而不是更改引用
cout << "a=" << a<
**作用:**函数传参时,可以利用引用的技术让形参修饰实参
**优点:**可以简化指针修改实参
示例:
#include
using namespace std;
// 1.值传递
void mySwap01(int a,int b)
{
int temp = b;
b = a;
a = temp;
}
// 2.地址传递
void mySwap02(int *a,int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
// 3.引用传递
void mySwap03(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
//mySwap01(a, b); 值传递,形参不会修饰实参
//mySwap02(&a, &b); // 地址传递,形参会修饰实参
mySwap03(a, b); // 引用传递,形参会修饰实参
cout << "a=" << a <
**作用:**引用是可以作为函数的返回值存在的
**注意:**不要返回局部变量引用
**用法:**函数调用作为左值
#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 << endl; // 第一次结果正确,是因为编译器做了保留
//cout << ref << endl; // 第二次结果错误,因为a的内存已经释放
int &ref = test02();
cout << ref << endl;
cout << ref << endl;
test02() = 1000;
cout << ref << endl;
cout << ref << endl;
system("pause");
return 0;
}
本质:引用的本质在C++内部实现是一个指针常量
**作用:**常量引用主要用来修饰形参,防止误操作
在函数形参列表中,可以加const修饰形参,防止形参改变实参
示例:
#include
using namespace std;
int main()
{
// 常量引用
// 使用场景:用来修饰形参,防止误操作
// int a = 10;
// 加上const后 编译器将代码修改 int temp = 10; const int & ref = temp;
// ref = 20; //加入const之后变为只读,不可以修改
system("pause");
return 0;
}
在C++中,函数的形参列表中的形参是可以有默认值的。
语法:返回值类型 函数名 (参数=默认值){}
#include
using namespace std;
int func(int a, int b=20, int c=30)
{
return a + b + c;
}
int main()
{
cout << func(0) << endl;
system("pause");
return 0;
}
注意事项:
C++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置
语法:返回值类型 函数名 (数据类型){}
在现阶段函数的占位参数存在意义不大,但是后面的课程中会用到该技术
示例:
#include
using namespace std;
// 占位参数
// 返回值类型 函数名(数据类型){}
void func(int a ,int)
{
cout << "this is func" << endl;
}
int main()
{
func(10, 10);
system("pause");
return 0;
}
**作用:**函数名可以相同,提高复用性
函数重载满足条件:
**注意:**函数的返回值不可以作为函数重载的条件
示例:
#include
using namespace std;
// 函数重载
// 可以让函数名相同,提高复用性
// 函数重载的满足条件
// 1、同一个作用域下
// 2、函数名称相同
// 3、函数参数类型不同
void func(){
cout << "func的调用" << endl;
}
void func(int a)
{
cout << "func(int a)的调用" << endl;
}
void func(double a)
{
cout << "func(double a)的调用" << endl;
}
int main()
{
func();
func(10);
func(3.14);
system("pause");
return 0;
}
示例:
#include
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 =10)
{
cout << "fun2(int a)" << endl;
}
void fun2(int a)
{
cout << "fun2(int a =20)" << endl;
}
int main()
{
int a = 10;
fun(a);
fun(10);
//fun2(10); // 碰到默认参数产生歧义,避免使用
system("pause");
return 0;
}
C++面向对象的三大特性为:封装、继承、多态
C++认为万事万物都皆为对象,对象上有其属性和行为
例如:
人可以作为对象,属性有姓名、年龄、身高、体重…,行为有走、跑、跳、吃饭、唱歌…
车也可以作为对象,属性有轮胎、方向盘、车灯…,行为有载人、放音乐、放空调…
具有相同性质的对象,我们可以抽象称为类,人属于人类,车属于车类
封装是C++面向对象三大特征之一
封装的意义:
封装的意义一:
在设计类的时候,属性和行为写在一起,表现事物
语法:class 类名{ 访问权限: 属性 / 行为};
示例:
#include
using namespace std;
// 圆周率
const double PI = 3.14;
// 设计一个圆类,求圆的周长
// 圆球周长的公式:2 * PI * 半径
// class 代表设计一个类,类后面紧跟着的就是类名称
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;
}
封装的意义二:
类在设计时,可以把属性和行为放在不同的权限下,加以控制
访问权限有三种:
示例:
#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 = "123456";
}
};
int main()
{
Person p1;
p1.func();
//p1.m_Car = "Benz"; // 保护权限内容,在类外访问不到
//p1.m_Password = "123"; // 私有权限内容,在类外访问不到
system("pause");
return 0;
}
在C++中struct和class唯一的区别就在于默认的访问权限不同
区别:
示例:
#include
using namespace std;
class C1
{
int m_A; // 默认权限 是私有
};
struct C2
{
int m_A; // 默认权限 是公有
};
int main()
{
// struct 和 class的区别
// struct 默认权限是 公共 public
// class 默认权限是 私有 private
C1 c1;
//c1.m_A = 100; // 在class默认权限 私有,因此类外不可访问
C2 c2;
c2.m_A = 100; // 在struct默认权限为公共,因此可以访问
system("pasue");
return 0;
}
**优点1:**将所有成员属性设置为私有,可以自己控制读写权限
**优点2:**对于写权限,我们可以检测数据的有效性
对象的初始化和清理也是两个非常重要的安全问题
一个对象或者变量没有初始状态,对其使用后果是未知
同样的使用完一个对象或变量,没有及时清理,也会造成一定的安全问题
C++利用了构造函数和析构函数解决上述问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。
对象的初始化和清理工作都是编译器强制要我们做的事情,因此如果我们不提供构造和析构,编译器会提供编译器提供的构造函数和析构函数是空实现。
构造函数语法:类名(){}
析构函数语法:~类名(){}
#include
using namespace std;
// 对象的初始化和清理
// 1、构造函数 进行初始化操作
class Person1
{
public:
//1.1、构造函数
// 没有返回值 不用写void
// 函数名与类名相同
// 构造函数可以有参数,可以发生重载
// 创建对象的时候,构造函数会自动调用,而且只调用一次
Person1()
{
cout << "Person1构造函数的调用" << endl;
}
// 2、析构函数 进行清理的操作
// 没有返回值 不写 void
// 函数名和类名相同 在名称前加 ~
// 析构函数不可以有参数的,不可以发生重载
// 对象在销毁前 会自动调用析构函数,而且只会调用一次
~Person1()
{
cout << "Person1析构函数的调用" << endl;
}
};
void test011()
{
Person1 p;
}
int main()
{
//test011();
Person1 p;
system("pause");
return 0;
}
两种分类方式:
按参数分为:有参构造和无参构造
按类型分为:普通构造和拷贝构造
三种调用方式:
括号法
显示法
隐式转换法
示例:
#include
using namespace std;
// 构造函数的分类及调用
// 分类
// 按照参数分类 无参构造(默认构造)和 有参构造
// 按照类型分类 普通构造 拷贝构造
class Per
{
public:
//构造函数
Per()
{
cout << "Pers的构造函数调用" << endl;
}
Per(int a)
{
cout << "Pers的有参构造函数调用" << endl;
}
// 拷贝构造函数
Per(const Per &p)
{
// 将传入的人身上的所有属性,拷贝到我身上
age = p.age;
cout << "拷贝构造函数" << endl;
}
~Per()
{
cout << "拷贝构造函数析构" << endl;
}
int age;
};
void test11()
{
// 1、括号法
//Per p111; // 默认构造函数调用
//Per p222(10); // 有参构造函数
//Per p333(p222); //拷贝构造函数
// 注意事项
// 调用默认构造函数时候,不要加()
// 因为下面这行代码,编译器会认为是一个函数的声明
//Per p1();
// 2、显示法
//Per p111;
//Per p222 = Per(10); //有参构造
//Per p333 = Per(p222); //拷贝构造
//Per(10); 匿名对象, 特点:当前执行结束后,系统会立即回收掉匿名对象
// 注意事项2:
// 不要利用拷贝构造函数 初始化匿名对象 编译器会认为 Per (p333) === Per p333 对象的声明
// 3、隐式转换法
Per p4 = 10; // 相当于 写了 Per p4 = Per(10); 有参构造
Per p5 = p4; // 拷贝构造
}
int main()
{
test11();
system("pause");
return 0;
}
C++中拷贝构造函数调用时机通常有三种情况
示例:
#include
using namespace std;
// 拷贝构造函数调用时机
class Person1
{
public:
Person1()
{
cout << "Person默认构造函数调用" << endl;
}
Person1(int age)
{
cout << "Person有参构造函数调用" << endl;
m_age = age;
}
Person1(const Person1 &p)
{
cout << "Person拷贝构造函数调用" << endl;
m_age = p.m_age;
}
~Person1()
{
cout << "Person析构函数调用" << endl;
}
int m_age;
};
// 1、使用一个已经创建完毕的对象来初始化一个新的对象
void test001()
{
Person1 p1(20);
Person1 p2(p1);
cout << p2.m_age << endl;
}
// 2、值传递的方式给函数参数传值
void doWork(Person1 p)
{
}
void test002()
{
Person1 p;
doWork(p);
}
// 3、值方式返回局部对象
Person1 doWork2()
{
Person1 p;
cout << (int*)&p << endl;
return p;
}
void test003()
{
Person1 p = doWork2();
cout << (int*)&p << endl;
}
int main()
{
test003();
system("pause");
return 0;
}
默认情况下,c++编译器至少给一个类添加3个函数
构造函数调用规则下:
示例:
#include
using namespace std;
// 构造函数的调用规则
// 1、创建一个类,C++会给每个类都添加至少3个函数
// 默认构造(空实现)
// 析构函数(空实现)
// 拷贝构造(值拷贝)
// 2、如果我们写了有参构造函数,编译器就不再提供默认构造,依然提供拷贝构造
class Person2
{
public:
/*Person2()
{
cout << "Person的默认构造函数调用" << endl;
}*/
Person2(int age)
{
m_age = age;
cout << "Person的默认构造函数调用" << endl;
}
//Person2(const Person2 &p)
//{
// m_age = p.m_age;
// cout << "Person的拷贝构造函数调用" << endl;
//}
~Person2()
{
cout << "Person的默认析构函数" << endl;
}
int m_age;
};
//void test100()
//{
// Person2 p;
// p.m_age = 18;
// Person2 p2(p);
// cout << "Person2的m_age" << p2.m_age << endl;
//}
void test200()
{
Person2 p(28);
Person2 p2(p);
cout << p2.m_age << endl;
}
int main()
{
//test100();
test200();
system("pause");
return 0;
}
深浅拷贝面是面试经典问题,也是常见的一个坑
浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
示例:
#include
using namespace std;
class Test
{
public:
Test()
{
cout << "Test默认构造函数" << endl;
}
Test(int a,int height)
{
m_age = a;
m_height = new int(height);
cout << "Test有参构造函数" << endl;
}
// 自己实现拷贝构造函数 解决浅拷贝带来的问题
Test(const Test &t)
{
cout << "Test拷贝构造函数的调用" << endl;
m_age = t.m_age;
//m_height = t.m_height; // 编译器默认实现的就是这行代码
// 深拷贝操作
m_height = new int(*t.m_height);
}
~Test()
{
// 析构代码,将堆区开辟数据做释放操作
if (m_height !=NULL)
{
delete m_height;
m_height = NULL;
}
cout << "Test析构函数" << endl;
}
int m_age;
int *m_height;
};
void show()
{
Test t(18,160);
cout << t.m_age <<"\t"<<*t.m_height<< endl;
Test t2(t);
cout << t2.m_age << "\t" << *t2.m_height << endl;
t2.m_age = 28;
cout << t.m_age << "\t" << *t.m_height << endl;
cout << t2.m_age << "\t" << *t2.m_height << endl;
}
int main()
{
show();
system("pause");
return 0;
}
作用:
C++提供了初始化列表语法,用来初始化属性
语法:构造函数():属性1(值1),属性2(值2),...{}
#include
using namespace std;
class Pe{
public:
// 传统初始化操作
/*Pe(int a,int b,int c)
{
m_a = a;
m_b = b;
m_c = c;
}*/
// 初始化列表初始化属性
Pe(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 showPe()
{
Pe p(10,20,30);
cout << p.m_a << endl;
cout << p.m_b << endl;
cout << p.m_c << endl;
}
int main()
{
showPe();
system("pause");
return 0;
}
C++类中的成员可以是另一个类的对象,我们称该成员为 对象成员
例如:
class A {}
class B
{
A a;
}
B类中有对象A作为成员,A为对象成员
那么当创建B对象时,A与B的构造和析构的顺序是谁先谁后?
示例:
#include
using namespace std;
#include
class A
{
public:
A(string aname)
{
a_name = aname;
}
string a_name;
};
class B
{
public:
B(string bname, string bson) : b_name(bname), b_son(bson)
{
}
string b_name;
A b_son;
};
// 当其他类对象作为本类成员,构造时候先构造类对象,再构造自身,析构顺序与构造相反
void showB()
{
B b("张三", "三星s23");
cout << b.b_name << endl;
cout << b.b_son.a_name << endl;
}
int main()
{
showB();
system("pause");
return 0;
}
静态成员就是在成员变量和成员函数前加上关键字static,称为静态成员
静态成员分为:
静态成员变量
静态成员函数
示例:
#include
using namespace std;
// 静态成员函数
// 所有对象共享同一个函数
// 静态成员函数只能访问静态成员变量
class CC
{
public:
static void func()
{
m_a = 100; // 静态成员函数可以访问 静态成员变量
//m_b = 200; // 静态成员函数 不可以访问 非静态成员变量 无法区分到底是哪个对象的m_b
cout << "static void func调用" << endl;
}
static int m_a;
int m_b;
};
void showCC()
{
// 1、通过对象访问
CC c;
c.func();
// 2、通过类名访问
CC::func();
// 类外访问不到私有的成员函数
}
int main()
{
showCC();
system("pause");
return 0;
}
在C++中,类内的成员变量和成员函数分开存储
只有非静态成员变量才属于类的对象上
示例:
#include
using namespace std;
class Demo1
{
int m_a; // 非静态成员变量 属于类的对象上
static int m_b; // 静态成员变量 不属于类的对象上
void func(){};
};
int Demo1::m_b = 100;
void showDemo1()
{
Demo1 d;
// 空对象占用内存空间为:1
// C++编译器会给每个空对象也分配一个字节空间
// 每个空对象也应该有一个独一无二的内存地址
cout << "size of d " << sizeof(d) << endl;
}
int main()
{
showDemo1();
system("pause");
return 0;
}
在C++中成员变量和成员函数是分开存储的
每一个非静态成员函数只会诞生一份函数实例,也就是说多个类型的对象会共用一块代码
那么问题是:这一块代码是如何区分哪个对象调用自己的呢?
C++通过提供特殊的对象指针,this指针,解决上述问题,this指针指向被调用的成员函数所属的对象
this指针是隐含每一个非静态成员函数内的一种指针
this指针不需要定义,直接使用即可
this指针的用途:
示例:
#include
using namespace std;
class Demo2
{
public:
Demo2(int age){
// this指针指向的是被调用的成员函数 所属的对象
this->age = age;
}
Demo2& PersonAddAge(Demo2 &d)
{
this->age += d.age;
return *this;
}
int age;
};
// 1、解决名称冲突
void showDemo2()
{
Demo2 d1(18);
cout << d1.age << endl;
}
// 2、返回对象本身用this
void show2Demo2()
{
Demo2 d1(10);
Demo2 d2(10);
// 链式编程
d2.PersonAddAge(d1).PersonAddAge(d1).PersonAddAge(d1).PersonAddAge(d1);
cout << d2.age << endl;
}
int main()
{
showDemo2();
show2Demo2();
system("pause");
return 0;
}
C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
示例:
#include
using namespace std;
// 空指针调用成员函数
class Demo3
{
public:
void showClassName()
{
cout << "this is Demo3 class" << endl;
}
void showDemo3Age()
{
// 报错的原因是传入的指针是NULL
if (this == NULL) return;
cout << "age=" << m_Age << endl;
}
int m_Age;
};
void showDemo3()
{
Demo3 * d = NULL;
d->showClassName();
d->showDemo3Age();
}
int main()
{
showDemo3();
system("pause");
return 0;
}
常函数:
常对象:
示例:
#include
using namespace std;
// 常函数
class Demo4
{
public:
// this指针的本质 是指针常量 指针的指向是不可以修改的
// 在成员函数后面加const,修饰的是this指向,让指针指向的值也不可以修改
void show() const
{
this->m_B = 100;
// this->m_A = 100;
// this = NULL; // this指针不可以修改指针的指向
}
void func(){};
int m_A;
mutable int m_B; // 特殊变量,即使在常常函数中,也可以修改这个值,加mutable关键字
};
void showDemo4_01()
{
Demo4 d;
d.show();
}
// 常对象
void showDemo4_02()
{
const Demo4 d; // 在对象前加const,变为常对象
// d.m_A = 100;
d.m_B = 100; // m_B是特殊值,在常对象下也可以修改
// 常对象只能调用常函数
d.show();
//d.func(); // 常对象 不可以调用普通成员函数,因为普通成员函数可以修改属性
}
int main()
{
system("pause");
return 0;
}
在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
友元的目的就是让一个函数或者类 访问另一个类中私有成员
友元的关键字为friend
友元的三种实现
#include
using namespace std;
#include
class Demo5
{
// goodGay全局函数是Demo5的好朋友,可以访问Building中私有成员
friend void goodGay(Demo5 *d);
public:
Demo5()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom; // 客厅
private:
string m_BedRoom; // 卧室
};
// 全局函数
void goodGay(Demo5 *d)
{
cout << "正在访问:" << d->m_SittingRoom << endl;
cout << "正在访问:" << d->m_BedRoom << endl;
}
void showDemo5()
{
Demo5 d;
goodGay(&d);
}
int main()
{
showDemo5();
system("pause");
return 0;
}
#include
using namespace std;
#include
class Demo6;
// 类做友元
class GoodGay
{
friend class Demo6;
public:
GoodGay();
void visit();
Demo6 *d6;
};
class Demo6
{
// GoodGay是本类的好朋友可以访问本类中的私有变量
friend class GoodGay;
public:
Demo6();
string m_SittingRoom;
private:
string m_BedRoom;
};
// 类外写成员函数
Demo6::Demo6()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
d6 = new Demo6;
}
void GoodGay::visit()
{
cout << "正在访问:" << d6->m_SittingRoom <m_BedRoom<
#include
using namespace std;
#include
class Demo7;
class Demo8
{
public:
Demo8();
Demo7 *d7;
void visit(); // 让visit函数可以访问Demo7中的私有成员变量
void visit2(); // 这个不能访问私有成员
};
class Demo7
{
// 告诉编译器 Demo8下的visit成员函数作为本类的好朋友 可以访问私有成员
friend void Demo8::visit();
public:
Demo7();
public:
string m_SittingRoom; // 客厅
private:
string m_Bedroom; // 卧室
};
Demo7::Demo7()
{
m_SittingRoom = "SittingRoom";
m_Bedroom = "BedRoom";
}
Demo8::Demo8()
{
d7 = new Demo7;
}
void Demo8::visit()
{
cout << "visit 正在访问:" << d7->m_SittingRoom << endl;
cout << "visit 正在访问:" << d7->m_Bedroom << endl;
}
void Demo8::visit2()
{
cout << "visit2 正在访问:" << d7->m_SittingRoom << endl;
cout << "visit 正在访问:" << d7->m_Bedroom << endl; //会报错
}
void showDemo8()
{
Demo8 d8;
d8.visit();
d8.visit2();
}
int main()
{
showDemo8();
system("pause");
return 0;
}
运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
作用:实现两个自定义数据类型相加的运算
示例:
#include
using namespace std;
// 加号运算符重载
class Person
{
// 1、成员函数重载+号
public:
/*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_B;
temp.m_B = p1.m_B + p2.m_B;
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;
cout << p3.m_A << endl;
cout << p3.m_B << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
作用:可以输出自定义数据类型
示例:
#include
using namespace std;
class Person02
{
friend ostream &operator<<(ostream &cout, Person02 &p);
// 利用成员函数重载左移运算符 p.operator<<(cout) 简化版本 p << cout
// 不会利用成员函数重载<<运算符,因为无法实现cout在左侧
public:
Person02(int a,int b)
{
m_A = a;
m_B = b;
}
private:
int m_A;
int m_B;
};
ostream &operator<<(ostream &cout, Person02 &p)
{
cout << "m_A= " << p.m_A << " m_B= " << p.m_B;
return cout;
}
void showPerson02()
{
Person02 p(10,10);
cout << p <
作用:通过重载递增运算符,实现自己的整型数据
示例:
#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 showMyInteger()
{
MyInteger myInt;
cout << ++myInt << endl;
}
void showMyInteger02()
{
MyInteger myInt;
cout << myInt++ << endl;
cout << myInt << endl;
}
int main()
{
//showMyInteger();
showMyInteger02();
system("pause");
return 0;
}
C++编译器至少给一个类添加4个函数
如果类中有属性指向堆区,做赋值操作时也会出现是深浅拷贝问题
示例:
#include
using namespace std;
// 赋值运算符重载
class Person04
{
public:
Person04(int age)
{
m_Age = new int(age);
}
~Person04()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
Person04 & operator=(Person04 &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 showPerson04()
{
Person04 p1(18);
Person04 p2(10);
Person04 p3(30);
p3 = p1 = p2;
cout << "p1的年龄是:" << *p1.m_Age << endl;
cout << "p2的年龄是:" << *p2.m_Age << endl;
cout << "p2的年龄是:" << *p3.m_Age << endl;
}
int main()
{
showPerson04();
system("pause");
return 0;
}
**作用:**重载关系运算符,可以让两个自定义类型对象进行对比操作
示例:
#include
using namespace std;
#include
// 关系运算符重载
class Person05
{
friend bool operator==(Person05 &p1, Person05 &p2);
public:
Person05(string name,int age)
{
m_Name = name;
m_Age = age;
}
private:
string m_Name;
int m_Age;
};
bool operator==(Person05 &p1, Person05 &p2)
{
if (p1.m_Name == p2.m_Name && p1.m_Age == p2.m_Age)
{
return true;
}
return false;
}
void showPerson05()
{
Person05 p1("萨达", 20);
Person05 p2("达", 10);
if (p1 == p2)
{
cout << "相等" << endl;
}
else
{
cout << "不相等" << endl;
}
}
int main()
{
showPerson05();
system("pause");
return 0;
}
示例:
#include
using namespace std;
#include
// 重载函数调用运算符
class MyPrint
{
public:
void operator()(string text)
{
cout << text << endl;
}
};
void showMyPrint()
{
MyPrint myprint;
myprint("hello");
}
int main()
{
showMyPrint();
system("pause");
return 0;
}
继承是面向对象三大特性之一
示例:
#include
using namespace std;
class BaseIndex
{
public:
void header()
{
cout << "首页头部" << endl;
}
void footer()
{
cout << "首页底部" << endl;
}
};
class Java:public BaseIndex
{
public:
void show()
{
cout << "java" << endl;
}
};
class CPP :public BaseIndex
{
public:
void show()
{
cout << "CPP" << endl;
}
};
class PY :public BaseIndex
{
public:
void show()
{
cout << "PY" << endl;
}
};
// 继承的好处:减少重复代码
// 语法:class 子类:继承方式 父类
// 子类 也称为 派生类
// 父类 也称为 基类
void showIndex()
{
Java ja;
ja.header();
ja.show();
ja.footer();
cout << "-------------" << endl;
CPP cpp;
cpp.header();
cpp.show();
cpp.footer();
cout << "-------------" << endl;
PY py;
py.header();
py.show();
py.footer();
}
int main()
{
showIndex();
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 = 10; // 父类中的保护权限成员 到子类中依然是保护权限
//m_c = 10; // 父类中的私有权限成员 子类访问不到
}
};
// 保护继承
class Son2 :protected Base1
{
public:
void func()
{
m_a = 20;
m_b = 20;
//m_c = 20; // 父类中私有成员 子类访问不到
}
};
// 私有继承
class Son3:private Base1
{
public:
void func()
{
m_a = 30; // 父类中公共成员 到子类中变为 私有成员
m_b = 30; // 父类中保护成员 到子类中变为 私有成员
//m_c = 30;// 父类中私有成员 子类访问不到
}
};
void test01()
{
Son1 s1;
s1.m_a = 100;
//s1.m_b = 100; // 到Son1中 m_b是保护权限 类外访问不到
}
void test02()
{
Son2 s2;
//s2.m_a = 100; // 在Son2中m_a变为保护权限,因此类外访问不到
//s2.m_b = 100; // 在Son2中m_b变为保护权限,因此类外访问不到
}
void test03()
{
Son3 s3;
//s3.m_a = 1000; // 在Son3中m_a变为私有权限,因此类外访问不到
//s3.m_b = 1000; // 在Son3中m_a变为私有权限,因此类外访问不到
//s3.m_c = 1000; // 父类中私有权限 子类访问不到
}
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;
};
// 利用开发人员命令提示工具查看对象模型
// 跳转盘符
// 跳转文件路径 cd 具体路径下
// 查看命名 dir
// cl /d1 reportSingleClassLayout类名
void showSon()
{
Son s;
// 父类中所有非静态成员属性都会被子类继承下去
// 父类中私有成员属性 是被编译器给隐藏了,因此是访问不到,但是确实被继承下去了
cout << "Son sizeof = " << sizeof(s) << endl;
}
int main()
{
showSon();
system("pause");
return 0;
}
子类继承父类后,当创建子类对象,也会调用父类的构造函数
问题:父类和子类的构造和析构顺序谁先谁后
示例:
#include
using namespace std;
// 继承中的继承和析构顺序
class Base2
{
public:
Base2()
{
cout << "Base构造函数" << endl;
}
~Base2()
{
cout << "Base析构函数" << endl;
}
};
class BaseSon :public Base2
{
public:
BaseSon()
{
cout << "BaseSon构造函数" << endl;
}
~BaseSon()
{
cout << "BaseSon析构函数" << endl;
}
};
void showBason()
{
BaseSon bs;
// 继承中的构造和析构顺序如下:
// 先构造父类,再构造子类,析构的顺序与构造的顺序相反
}
int main()
{
showBason();
system("pause");
return 0;
}
问题:当子类与父类出现同名的成员,如何通过子类对象,访问到子类或父类中同名的数据呢?
示例:
#include
using namespace std;
//继承中同名成员的处理方式
class Father
{
public:
Father()
{
m_a = 100;
}
void func(){
cout << "father" << endl;
}
void func(int a)
{
m_a = a;
}
int m_a;
};
class Child:public Father
{
public:
Child()
{
m_a = 200;
}
void func()
{
cout << "child" << endl;
}
int m_a;
};
// 成员属性的处理方式
void showChild()
{
Child c;
cout << c.m_a << endl;
// 如果通过子类对象 访问父类中同名成员,需要加作用域
cout << c.Father::m_a << endl;
c.func();
// 如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中所有同名成员函数
// 如果想访问到父类中被隐藏的同名成员函数,需要加作用域
c.Father::func();
c.Father::func(200);
}
// 成员函数的处理方式
int main()
{
showChild();
system("pause");
return 0;
}
总结:
问题:继承中同名的静态成员在子类对象上如何进行访问?
静态成员和非静态成员出现同名,处理方式一致
示例:
#include
using namespace std;
class BaseStatic
{
public:
static void func()
{
cout << "BaseStatic func" << endl;
}
static void func(int a)
{
cout << a << endl;
}
static int m_a;
};
int BaseStatic::m_a = 100;
class NextStatic:public BaseStatic
{
public:
static void func()
{
cout << "NextStatic func" << endl;
}
static int m_a;
};
int NextStatic::m_a = 200;
void showNextStatic()
{
NextStatic ns;
// 1、通过对象访问
cout << ns.m_a << endl;
cout << ns.BaseStatic::m_a << endl;
ns.func();
ns.BaseStatic::func();
// 2、通过类名访问
cout << NextStatic::m_a << endl;
// 第一个::代表通过类名方式访问 第二个::代表访问父类作用域下
cout << NextStatic::BaseStatic::m_a << endl;
NextStatic::func();
NextStatic::BaseStatic::func();
// 子类出现和父类同名静态成员函数,也会隐藏父类中所有同名成员函数
// 如果访问父类中被隐藏同名成员,需要加作用域
NextStatic::BaseStatic::func(100);
}
int main()
{
showNextStatic();
system("pause");
return 0;
}
C++允许一个类继承多个类
语法:class 子类:继承方式 父类1,继承方式 父类2...
多继承可能会引发父类中有同名成员出现,需要加作用域区分
C++实际开发中不建议使用多继承
示例:
#include
using namespace std;
class DaDie
{
public:
int m_a;
};
class ErDie
{
public:
int m_b;
};
class ErZi:public DaDie,public ErDie
{
public:
int m_c;
};
void showErZi()
{
ErZi e;
cout << sizeof(e) << endl;
}
int main()
{
showErZi();
system("pause");
return 0;
}
菱形继承概念:
两个派生类继承同一个积累
又有某个类同时继承这两个派生类
这种继承被称为菱形继承,或者钻石继承
示例:
#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 showSheepTuo()
{
SheepTuo st;
st.Sheep::m_Age =10;
st.Tuo::m_Age = 20;
// 当菱形继承,两个父类拥有相同数据,需要加以作用域区分
cout << st.Sheep::m_Age << endl;
cout << st.Tuo::m_Age << endl;
cout << st.m_Age << endl;
}
int main()
{
showSheepTuo();
system("pause");
return 0;
}
总结:
多态是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;
}
};
// 执行说话函数
// 地址早绑定 在编译阶段确定函数地址
// 如果想执行让猫说话,那么这个函数地址就不能提前绑定,需要在运行阶段进行绑定,地址晚绑定
void doSpeak(Animal &animal)
{
animal.speak();
}
// 动态多态满足条件
// 1、有继承关系
// 2、子类重写父类的虚函数
// 动态多态使用
// 父类的指针或者引用 执行子类对象
void showCat()
{
Cat cat;
doSpeak(cat);
Dog dog;
doSpeak(dog);
}
int main()
{
showCat();
system("pause");
return 0;
}
总结:
多态满足条件
多态使用条件
重写:函数返回值类型 函数名 参数列表 完全一致称为重写
案例描述:
分别利用普通写法和多态技术,实现两个操作数进行运算的计算器类
多态的优点:
示例:
#include
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;
}
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:
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 showCalculator()
{
Calculator c;
c.m_Num1 = 10;
c.m_Num2 = 10;
cout << c.getResult("+") << endl;
cout << c.getResult("-") << endl;
cout << c.getResult("*") << endl;
cout << c.getResult("/") << endl;
}
void showAC()
{
AbstractCalculator *abc = new AddCalculator;
abc->m_Num1 = 10;
abc->m_Num2 = 10;
cout << abc->getResult() << endl;
delete abc;
abc = new SubCalculator;
abc->m_Num1 = 10;
abc->m_Num2 = 10;
cout << abc->getResult() << endl;
delete abc;
abc = new MulCalculator;
abc->m_Num1 = 10;
abc->m_Num2 = 10;
cout << abc->getResult() << endl;
}
int main()
{
//showCalculator();
showAC();
system("pause");
return 0;
}
在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数
纯虚函数语法:virtual 返回值类型 函数名 (参数列表) = 0;
当类中有了纯虚函数,这个类也称为抽象类
抽象类特点:
示例:
#include
using namespace std;
// 纯虚函数和抽象类
class Base
{
public:
// 纯虚函数
// 只要有一个纯虚函数,这个类称为抽象类
// 抽象类特点
// 1、无法实例化对象
// 2、抽象类的子类 必须要重写父类中的纯虚函数,否则也属于抽象类
virtual void func() = 0;
};
class Son :public Base
{
public:
void func()
{
cout << "func" << endl;
}
};
void test01()
{
// Base b; // 抽象类无法化实例对象
// new Base; // 抽象类无法化实例对象
//Son s; // 子类必须重写父类中的纯虚函数,否则无法实例化对象
Base *b = new Son;
b->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 BoilTea:public AbstractDrinking
{
void Boil()
{
cout << "烧水100%" << endl;
}
void Brew()
{
cout << "冷却80℃" << endl;
}
void PourInCup()
{
cout << "倒水冲茶叶" << endl;
}
void PutSomething()
{
cout << "加点枸杞" << endl;
}
};
class BoilCoffee :public AbstractDrinking
{
void Boil()
{
cout << "烧水100%" << endl;
}
void Brew()
{
cout << "冷却80℃" << endl;
}
void PourInCup()
{
cout << "倒水冲咖啡" << endl;
}
void PutSomething()
{
cout << "加点牛奶" << endl;
}
};
// 制作
void doWork(AbstractDrinking &abc)
{
abc.makeDrink();
}
void test02()
{
BoilCoffee c;
doWork(c);
cout << "---------------------------------" << endl;
BoilTea t;
doWork(t);
}
int main()
{
test02();
system("pause");
return 0;
}
多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码
解决方式:将父类中的析构函数改为虚析构或者纯虚析构
虚析构和纯虚析构共性
虚析构和纯虚析构区别:
虚析构语法:
virtual ~类名(){}
纯虚析构语法:
virtual ~类名() = 0;
类名::~类名(){}
示例:
#include
using namespace std;
#include
class A
{
public:
A()
{
cout <<"A的构造" << endl;
}
// 利用虚析构可以解决 父类指针释放子类对象时不干净的问题
/*virtual ~A()
{
cout << "A的虚析构" << endl;
}*/
// 纯虚析构 需要声明也需要实现
virtual ~A() = 0;
virtual void speak() = 0;
};
A::~A()
{
cout << "A的纯虚析构" << endl;
}
class C:public A
{
public:
C(string name)
{
cout << "C的构造" << endl;
m_Name = new string(name);
}
~C()
{
if (m_Name != NULL)
{
cout << "C的析构" << endl;
delete m_Name;
m_Name = NULL;
}
}
void speak()
{
cout <<*m_Name <<"小猫在说话" << endl;
}
string *m_Name;
};
void showC()
{
A *a = new C("tom");
a->speak();
// 父类指针在析构时候 不会调用子类中析构哈数,导致子类如果有堆区属性,出现内存泄露
delete a;
}
int main()
{
showC();
system("pause");
return 0;
}
示例:
#include
using namespace std;
// 抽象出每个零件的类
class CPU
{
public:
virtual void calculate() = 0;
};
class VideoCard
{
public:
virtual void dispaly() = 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_m = mem;
}
void work()
{
m_cpu->calculate();
m_vc->dispaly();
m_m->storage();
}
~Computer()
{
if (m_cpu != NULL)
{
delete m_cpu;
m_cpu = NULL;
}
if (m_vc != NULL)
{
delete m_vc;
m_vc = NULL;
}
if (m_m != NULL)
{
delete m_m;
m_m = NULL;
}
}
private:
CPU *m_cpu;
VideoCard *m_vc;
Memory *m_m;
};
class InterCPU:public CPU
{
public:
virtual void calculate()
{
cout << "Inter_CPU_Working" << endl;
}
};
class InterVideoCard :public VideoCard
{
public:
virtual void dispaly()
{
cout << "Inter_VideoCard_Working" << endl;
}
};
class InterMemory :public Memory
{
public:
virtual void storage()
{
cout << "Inter_Memory_Working" << endl;
}
};
void showCpomputer()
{
CPU *interCpu = new InterCPU;
VideoCard *interVc = new InterVideoCard;
Memory *interMem = new InterMemory;
Computer *c = new Computer(interCpu, interVc, interMem);
c->work();
delete c;
}
int main()
{
showCpomputer();
system("pause");
return 0;
}
程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放
通过文件可以将数据持久化
C++中对文件操作需要包含头文件
文件类型分为两种:
操作文件的三大类:
写文件步骤如下:
包含头文件
#include
创建流对象
ofstream ofs;
打开文件
ofs.open(“文件路径”,打开方式);
写数据
ofs<<“写入数据”;
关闭文件
ofs.close();
文件打开方式:
打开方式 | 解释 |
---|---|
ios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 追加方式写文件 |
ios::trunc | 如果文件存在先删除,再创建 |
ios::binary | 二进制方式 |
**注意:**文件打开方式可以配合使用,利用|操作符
‘示例:
#include
using namespace std;
#include
void test01()
{
// 1.包含头文件
// 2.创建流对象
ofstream ofs;
// 3.打开文件
ofs.open("text.txt", ios::out);
// 4.写数据
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:23" << endl;
// 5.关闭文件
ofs.close();
}
int main()
{
test01();
system("pause");
return 0;
}
总结:
读文件与写文件步骤相似,但是读取方式相对于比较多
读文件步骤如下
包含头文件
#include
创建流对象
ifstream ifs;
打开文件并判断文件是否被打开
ifs.open("文件路径",打开方式);
读数据
四种方式读取
关闭文件
ifs.close();
示例:
#include
using namespace std;
#include
#include
// 文本文件 读文件
void test02()
{
//1、包含头文件
//2、创建流对象
ifstream ifs;
//3、打开文件 并且判断是否打开成功
ifs.open("text.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) // end of file
{
cout << c;
}
//5、关闭文件
ifs.close();
}
int main()
{
test02();
system("pause");
return 0;
}
以二进制的方式对文件进行读写操作
打开方式要指定为ios::binary
二进制方式写文件写文件主要利用流对象调用成员函数write
函数原型:ostream& write(const char *buffer,int len);
参数解释:字符指针buffer指向内存中一段存储空间,len是读写的字节数
示例:
#include
using namespace std;
#include
class Person
{
public:
char m_name[64];
int m_age;
};
void test03()
{
//1、包含头文件
//2、创建流对象
ofstream ofs("Person.txt", ios::out | ios::binary);
//3、打开文件
//ofs.open("Person.txt", ios::in | ios::binary);
//4、写文件
Person p = { "张三", 18 };
ofs.write((const char*)&p, sizeof(Person));
//5、关闭文件
ofs.close();
}
int main()
{
test03();
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 test04()
{
//1、包含头文件
//2、创建流对象
ifstream ifs("Person.txt", ios::in | ios::binary);
//3、打开文件
//ofs.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 << endl;
cout << p.m_age << endl;
//5、关闭文件
ifs.close();
}
int main()
{
test04();
system("pause");
return 0;
}