目录
1.智能指针
#include<memory>
1.作用
int *p=new int; //堆空间申请以后,使用完毕记得释放,如果程序员一直申请,从来都没有释放,会导致内存泄漏(没有多余的堆空间)
为了解决程序员容易忘记释放堆空间的毛病,C++发明了智能指针
原理
所谓的智能指针,本质是个模板类,在类的构造函数中自动帮你申请堆空间,在类的析构函数中自动帮你释放堆空间,程序员不必操心堆空间的释放问题
template<typename T>
class unique_ptr
{
public:
unique_ptr(参数)
{
point=new 参数;
}
~unique_ptr()
{
delete 释放指针堆空间;
}
private:
T *point;
};2.常用的智能指针
老版本的C++(C++11之前)
auto_ptr<模板类型> 对象(实参);
auto_ptr<int> p(new int);
*p=666;
C++11新增的智能指针
unique_ptr<模板类型> 对象();
unique_ptr<int> p(new int); //分配一个int大小的堆空间
unique_ptr<int[]> p(new int[10]);
p[0]=15; //*p
p[1]=56; //*(p+1)
p[2]=89;
#include<iostream>
#include<memory>
using namespace std;
int main()
{
//定义智能指针对象
auto_ptr<int> p(new int);
*p=666;
}
2.类型转换
1.以下四种都是模板函数
dynamic_cast //用于父类指针指向子类对象的转换(多态)(本来可以自动转换,不需要使用这个函数,但是规范写法还是写上)
父类 *p=dynamic_cast<父类 *>(子类指针);
const_cast //用于把一个const修改的指针,赋值给一个非const修饰的指针
People people1;
const People *p=&people1;
//People *q=p; 编译语法错误
People *q=const_cast<People *>(p);
static_cast //子类指针指向父类的转换
static_cast<类型1>(类型2)
reinterpret_cast //强制转换,跟你的C语言(强制转换)一样
struct student a={"张三",18};
struct student *p=&a;
C语言 char *q=(char *)p;
C++ char *q=reinterpret_cast<char *>(p);
注意: 实现文件拷贝(如果拷贝大文件,需要循环读取,循环写入)
判断文件是否读取完毕--》eof()--》读取完毕返回true
gcount()方法干什么 --》返回read成功读取的字节数
#include<iostream>
using namespace std;
class Animal
{
};
class Cat:public Animal
{
};
int main()
{
Cat c;
Animal *p=dynamic_cast<Animal *>(&c);
}
#include<iostream>
using namespace std;
int main()
{
string str="helloworld";
//string类型的字符串转换成char*
//char *p=str.c_str(); 编译语法错误,c_str返回值是const char*,但是p不是const修饰的指针
char *p=const_cast<char *>(str.c_str());
}
#include<iostream>
using namespace std;
class Animal
{
};
class Cat:public Animal
{
};
int main()
{
Animal a;
//子类指针指向父类
Cat *p=static_cast<Cat *>(&a);
}