static_cast运算符

static_cast记法是想代替(T)e,主要用于从基类到派生类的转换,我们都知道这种转换可能是不安全。但是这种转换经常是安全,甚至在缺乏运行时检查的情况下也是定义良好的。
例如:
#include <iostream>
using namespace std;
class A
{
public :
void print() { cout << "this is A" << endl; }
};
class B : public A
{
public :
void print() {cout << "this is B" << endl; }
};
void f(A *a, B *b)
{
 B *bb = static_cast<B *>(a);
 b->print();
 bb->print();
}
int main()
{
 A *a = new A;
 B *b = new B;
 f(a, b);
 system("PAUSE");
 return 0;
}



理解static_cast的一种方式就是将它看成隐式转换的逆运算的显式表达。除了不能处理常量性之外,只要B->A能够隐式的完成,static_cast就能做A->B。也就意味着在大部分情况下,static_cast能够直接使用。因为一般来说,派生类都能隐式的转换成基类。除此之外,所有可以隐式执行地转换,例如各种标准转换(int和long),也可以用static_cast,例如:
#include <iostream>
using namespace std;
int main()
{
 double d = 0.0;
 int i = static_cast<double>(d);
 cout << "d's size : " << sizeof(d) << endl;
 cout << "i's size : " << sizeof(i) << endl;
 system("PAUSE");
 return 0;
}



需要注意的是,使用static_cast在一个指针和一个类型之间转换时,如果这个类型的定义是看不到的讲会出错。
例如:
class X;
class Y;

void g(X *px)
{
 Y *py = (Y *)py;                        //allow, dangerous
 py = static_cast<Y *>(px);      //error : X and Y undefined
}
这就清清除了一类错误,,如果需要强制转换一个不完全的类型,那就用reinterpret_cast说清楚你并不是想在类层次上穿行,或者该用dynamic_cast;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值