c++ static_cast类型转换

本文详细介绍了C++中static_cast操作符的三种主要用途:基本类型转换,包括void*指针转换;有继承关系的类对象及指针转换;使用explicit修饰的构造函数进行类型转换。并通过具体代码示例展示了每种情况下的正确和错误用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、用于基本类型的转换,不能用于基本类型指针间的转换

虽然不能作用于基本类型指针,但是可以作用于void* 指针的转换。

#include <iostream>

using namespace std;


int main()
{
	int i = 0x12345;
	char c = 'c';
	int* pi = &i;
	char* pc = &c;

	c = static_cast<char>(i); //将int类型转化为char类型
	cout << c << endl;
	//pc = static_cast<char*>(pi); //error

	float fNum = 2.345;
	void* pv = &fNum;
	float * fp = static_cast<float *>(pv); //转化void * 指针

	cout << *fp << endl;

	return 0;
}

运行结果

E
2.345

 

2、用于有继承关系类对象之间的转换和类指针之间的转换

#include <iostream>

using namespace std;

class Parent
{

};

class Child : public Parent
{

};

class Other
{

};


int main()
{
	Parent parent;
	Child child;
	Other other;

	Parent *p1 = static_cast<Parent *>(&child);  //这两种写法没问题 但是结果无法预估
	Child *p2 = static_cast<Child *>(&parent);

	//此段代码无法通过编译  “static_cast” : 无法从“Child *”转换为“Other *” 因为Other类和Child类没有继承关系
	//Other *p3 = static_cast<Other *>(&child); 


	return 0;
}

 

3、用于使用explict修饰的构造函数

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int mValue;
public:
    Test()
    {
        mValue = 0;
    }
    
	//explicit 参数用于杜绝编译器的隐式转换
    explicit Test(int i) // 一个参数的构造函数被称为转换构造函数
    {
        mValue = i;
    }
    
    Test operator + (const Test& p)
    {
        Test ret(mValue + p.mValue);
        
        return ret;
    }
    
    int value()
    {
        return mValue;
    }
};

int main()
{   
    Test t;
    
    //t = 5 这种写法将会直接报错
    t = static_cast<Test>(5);    //等效于 t = Test(5);
    
    Test r;
    
    r = t + static_cast<Test>(10);   //等效于 r = t + Test(10);
    
    cout << r.value() << endl;
    
    return 0;
}

运行结果

15

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值