C++ const_cast,static_cast、dynamic_cast、reinterpret_cast的关系

一、static_cast

相关类型转换:

double f = 13.14f;
int i = static_cast<int> f;

父类转子类:

子类* p2 = static_cast<父类*>(p);

 

二、const_cast

不能去除常量的常量性:

const int i = 100;
int i = const_cast<int> i;//这是不行的,不是指针和引用

去除引用的常量性:

int k = 1;
const int & j = k;
int &qq = const_cast<int &>(j);
qq = 2;
cout << k << endl; //输出为2

去除指针的常量性:

int k = 1;
const int * j = &k;
int * qq = const_cast<int *>(j);
*qq = 2;
cout << k << endl;//输出为2

去除类的常量性:

class CCTest {
public:
   void setNumber( int );
   void printNumber() const ;
private:
   int number;
};
 
void CCTest::setNumber( int num ) { number = num; }
 
void CCTest::printNumber() const {
   cout << "\nBefore: " << number;
   const_cast< CCTest * >( this )->number--;
   cout << "\nAfter:" << number;
}

在const成员函数中不能修改成员变量。const成员函数中this 指针的数据类型为 const CCTest *,通过const_cast改变为CCTest *,这样就可以改变类的成员函数了。

 

三、dynamic_cast

class Human {
	virtual void talk();
};

class WoMen : public Human {
	void talk();
};

int main()
{
    Human *human = new WoMen();
    WoMen *pMen = dynamic_cast<WoMen*>(human);
    if (pMen != nullptr)
    {
        cout << "find" << endl;
    }
    else 
    {
        cout << "not find" << endl;
    }
}

dynamic_cast转换的类型必须有virtual方法。 

四、reinterpret_cast

将操作数的一种类型转换为另一种类型。

int i = 10;
int *pi = &i;
char * pvoid = reinterpret_cast<char *>(pi);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值