c语言cast的用法,static_cast 用法

static_cast 用法

语法:

static_cast(expression)

仅当 type-name 可以隐式转换为 expression 所属的类型,或者 expression 可以隐式转换为 type-name 所属的类型,转换才是合法的。否则,编译器会报错。

可以将有继承关系的派生类对象的地址赋给基类指针。即使基类中没有虚函数也可以使用 static_cast 进行转换。

可以将有继承关系的基类对象的地址赋给派生类指针。因为派生类指针可以隐式转换为基类指针,无需显式类型转换,所以可以用  static_cast 进行另一个方向的转换,即将基类指针转换为派生类指针。但是,这样做有什么意义呢?

同理,因为枚举值可以隐式转换为整型,无需显式类型转换,所以可以用 static_cast 将整型转换为枚举类型。

如果将没有继承关系的对象的地址赋给另一个类的指针,编译器会报错。

请看代码一:#include

class Base{

int dat;

public:

explicit Base(int val) : dat(val){

printf("%s, this=%p\n", __func__, this);

}

#if 0

virtual void act(){

#else

void act(){

#endif

printf("%s, this=%p\n", __func__, this);

}

};

class Sub : public Base{

public:

explicit Sub(int val) : Base(val){

printf("%s, this=%p\n", __func__, this);

}

};

class Other{

int dat;

public:

explicit Other(int val) : dat(val){

printf("%s, this=%p\n", __func__, this);

}

};

int main(){

Base obase(1);

Sub osub(2);

Base *pbase = NULL;

if(pbase = static_cast(&osub) ){

pbase->act();

}

printf("---------------\n");

Base *ptr = &osub;

ptr->act();

printf("---------------\n");

#if 1

if(Sub *psub = static_cast(&obase) ){

psub->act();

}

#endif

#if 0

Other oother(3);

//error: invalid static_cast from type ‘Other*’ to type ‘Base*’

if(pbase = static_cast(&oother) ){

pbase->act();

}

#endif

}

测试结果:

frank@userver:~/project/test/cpp/rtti$ ./a.out

Base, this=0x7fff6d478100

Base, this=0x7fff6d478110

Sub, this=0x7fff6d478110

act, this=0x7fff6d478110

---------------

act, this=0x7fff6d478110

---------------

act, this=0x7fff6d478100

代码二:#include

int main(){

enum eSource{

eAuxSource = 0,

eOpticalSource,

eBtSource,

eFcSource,

eSpotifySource,

eGcSource

};

#if 0

eSource src = eBtSource;

#else

//eSource src = 3; //error: invalid conversion from ‘int’ to ‘main()::eSource’ [-fpermissive]

eSource src = static_cast(3.1);

#endif

printf("src: %p, %lu, %d\n", &src, sizeof(src), src);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值