首页 / 软件开发 / C++ / C++类型转换运算符的使用方法
C++类型转换运算符的使用方法2011-04-28 本站整理 C++提供了四个新的类型转换运算符:const_castdynamic_castreinterpret_caststatic_cast使用方法:cast_operator <type> (object)类型转换操作符 要转换的类型 要进行转换的对象①dynamic_cast 将一个基类引用或指针转换位一个派生类应用或指针,或者将一个派生类引用或指针转换为一个基类引用或指针。例:class Shape { ... };
class Circle : public Shape { ... };
Shape *sp;
Circle *cp = dynamic_cast <Circle*> (sp);
class Control { ... };
class TextBox : public Control { ... };
Control &cr;
TextBox &ctl = dynamic_cast <Control&> (cr);
② static_cast 不局限于同一多态类层次中的基类和派生类,可使用static_cast调用处于不同层次的类型之间的隐式转换。例:class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
D* pd2 = static_cast<D*>(pb); // not safe, pb may
// point to just B
B* pb2 = static_cast<B*>(pd); // safe conversion
...
}
③ reinterpret_cast 将指针类型转换为其他指针类型,将数字转换为指针或将指针转换为数字。例:void * getmen()
{
static char buf[100];
…
return buf;
}
…
char *cp = reinterpret_cast<char *> (getmen);
④const_cast 移去对象的const, volatile, 和 __unaligned属性。例:class CCTest
{
public: void setNumber( int );
void printNumber() const;
private:
int number;
};
void CCTest::setNumber( int num )
{
number = num;
}
void CCTest::printNumber() const
{
cout << "
Before: " << number;
const_cast< CCTest * >( this )->number--;
cout << "
After: " << number;
}