原因:原始类型转换,所有情况都是一种写法,可读性不高,有可能有潜在的风险
static_cast 普遍情况
const_cast 去常量
dynamic_cast 子类类型转为父类类型
reinterpret_cast 函数指针转型,不具备移植性(有些编译器不支持转型)
static_cast
void* func(int type){
switch (type){
case 1: {
int i = 9;
return &i;
}
case 2: {
int a = 'X';
return &a;
}
default:{
return NULL;
}
}
}
void func2(char* c_p){
cout << *c_p << endl;
}
void main(){
//int i = 0;
//自动转换
//double d = i;
//double d = 9.5;
//int i = d;
//int i = 8;
//double d = 9.5;
//i = static_cast<int>(d);
//void* -> char*
//char* c_p = (char*)func(2);
//char* c_p = static_cast<char*>(func(2));
//C++ 意图明显
func2(static_cast<char*>(func(2)));
//C
func2((char*)(func(2)));
system("pause");
}
const_cast
void func(const char c[]){
//c[1] = 'a';
//通过指针间接赋值
//其他人并不知道,这次转型是为了去常量
//char* c_p = (char*)c;
//c_p[1] = 'X';
//提高了可读性
char* c_p = const_cast<char*>(c);
c_p[1] = 'Y';
cout << c << endl;
}
dynamic_cast
void func(Person* obj){
//调用子类的特有的函数,转为实际类型
//并不知道转型失败
//Man* m = (Man*)obj;
//m->print();
//转型失败,返回NULL
Man* m = dynamic_cast<Man*>(obj);
if (m != NULL){
m->chasing();
}
Woman* w = dynamic_cast<Woman*>(obj);
if (w != NULL){
w->carebaby();
}
}
reinterpret_cast
void func1(){
cout << "func1" << endl;
}
char* func2(){
cout << "func2" << endl;
return "abc";
}
typedef void(*f_p)();
void main(){
//函数指针数组
f_p f_array[6];
//赋值
f_array[0] = func1;
//C方式
//f_array[1] = (f_p)(func2);
//C++方式
f_array[1] = reinterpret_cast<f_p>(func2);
f_array[1]();
system("pause");
}
IO流
文本文件操作
void main(){
char* fname = "c://dest.txt";
//输出流
ofstream fout(fname);
//创建失败
if (fout.bad()){
return;
}
fout << "jack" << endl;
fout << "rose" << endl;
//关闭
fout.close();
//读取
ifstream fin(fname);
if (fin.bad()){
return;
}
char ch;
while (fin.get(ch)){
//输出
cout << ch;
}
fin.close();
system("pause");
}
//二进制文件
void main(){
char* src = "c://src.jpg";
char* dest = "c://dest.jpg";
//输入流
ifstream fin(src, ios::binary);
//输出流
ofstream fout(dest, ios::binary);
if (fin.bad() || fout.bad()){
return;
}
while (!fin.eof()){
//读取
char buff[1024] = {0};
fin.read(buff,1024);
//写入
fout.write(buff,1024);
}
//关闭
fin.close();
fout.close();
system("pause");
}
对象持久化
oid main()
{
Person p1("柳岩", 22);
//输出流
ofstream fout("c://c_obj.data", ios::binary);
fout.write((char*)(&p1), sizeof(Person)); //指针能够读取到正确的数据,读取内存区的长度
fout.close();
//输入流
ifstream fin("c://c_obj.data", ios::binary);
Person tmp;
fin.read((char*)(&tmp), sizeof(Person));
tmp.print();
system("pause");
}
网友评论