C++类型转换运算符的使用方法 |
|
www.nanhushi.com 佚名 不详 |
C++提供了四个新的类型转换运算符: const_cast dynamic_cast reinterpret_cast static_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 << "\nBefore: " << number; const_cast< CCTest * >( this )->number--; cout << "\nAfter: " << number; }
|
|
|
文章录入:杜斌 责任编辑:杜斌 |
|
上一篇文章: C++私有成员变量的访问权限研究 下一篇文章: c/c++语言实现堆栈修改,通过ret跳转到自定义函数 |
【字体:小 大】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 |
|
|