栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++: static

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++: static

static_cast比较接近于C语言中的强制转换,多用于不同的基本数据类型的转换:

char c1 = 0;
int i = static_cast(c1);
char c2 = static_cast(i);

他可以将空指针转换为目标类型的指针,或反之:

int i =0;
int *pa = &i;
void *pv = static_cast(pa);
int *pi = static_cast(pv);

但不能对不同类型的指针进行转换:

int i =0;
int *pa = &i;
char *pc = static_cast(pa);    //编译报错:invalid static_cast from type 'int*' to type 'char*
long *pl = static_cast(pa);    //编译报错:invalid static_cast from type 'int*' to type 'long int*'

更不能将整数转换为指针或反之:

int i =0;
int *pa = &i;
char *pc = static_cast(i);    //编译报错:invalid static_cast from type 'int' to type 'char*'
i = static_cast(pa);            //编译报错:invalid static_cast from type 'int*' to type 'int'

对于自定义类型,如果类定义转型运算符,那么也可以通过static_cast对类对象进行转型:

#include 
using namespace std;

class A{
public:
	operator int()
	{
		return 1;
	}
	operator char()
	{
		return 'a';
	}
};

int main()
{
	A a;
	int ai = static_cast(a);
	char ac = static_cast(a);
	cout<<"ai="<

对于自定义类型的指针,通过static_cast,将派生类指针转换为基类指针是安全的;反之,将基类指针转换为派生类指针是不安全的(建议类指针之间的转换都通过dynamic_cast进行)。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/960339.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号