c++类型转换

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>

 

using namespace std;

 

class Parent

{

public:

int a;

};

class Teacher

{

public:

int a;

int b;

};

 

class Test1

{

public:

static Test1 &set()

{

Test1 t;

return t;

}

int c;

int d;

private:

Test1()//构造函数私有化时,只能在类内部实例化,不能在类外部实例化了,可以创建一个公有静态成员函数,在这个函数里构建这个类的对象,注意一定要静态函数,应用场景:单例模式和工具类

{

a = 1;

b = 2;

}

int a;

int b;

};

class Test2 :public Test1

{

public:

void func()

{

Test1::c = 10;//这种用类作用域调用变量的,只能在继承中使用,且只能在子类的类里使用

}

};

 

//1.static_cast,一般的转换,适用于内置的基础数据类型,还有适用于具有继承关系的指针或引用

//2.dynamic_cast,通常在基类(父类)和派生类(子类)

//3.const_cast,主要针对const的转换

//4.reinterpret_cast,用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整数

int main()

{

//static_cast使用方法

int a = 10;

char b = static_cast<char>(a);

 

//static_cast不能转换指针类型的,但父子类型指针可以转换

//int *c = NULL;

//char *d = static_cast<char>(c);

 

//dynamic_cast使用方法

//只能用于转换继承关系的变量指针和引用,变量本身不支持,被static_cast作用包含

 

//const_cast使用方法

//可以使变量去const化,应用于指针和引用,也可以增加const性

const int e = 10;

int &d = const_cast<int &>(e);

d = 1;

const int *f = NULL;

int *g = const_cast<int *>(f);

 

//reinterpret_cast使用用方法

//无关系转换,但只能进行指针转换,实体对象类型不能转换,功能小于强转

Parent *h = NULL;

Teacher *i = NULL;

h = reinterpret_cast<Parent *>(i);

 

//一般不建议进行类型转换

 

Test1::set();

return 0;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值