C 类型转换运算符的使用方法

文章作者 100test 发表时间 2007:10:24 12:50:40
来源 100Test.Com百考试题网



C 提供了四个新的类型转换运算符:
const_cast dynamic_cast
reinterpret_cast static_cast

使用方法:cast_operator (object)
类型转换操作符 要转换的类型 要进行转换的对象
① dynamic_cast 将一个基类引用或指针转换位一个派生类应用或指针,或者将一个派生类引用或指针转换为一个基类引用或指针。
例:class Shape { ... }.
class Circle : public Shape { ... }.
Shape *sp;
Circle *cp = dynamic_cast (sp).

class Control { ... }.
class TextBox : public Control { ... }.
Control &.cr.
TextBox &.ctl = dynamic_cast (cr).

② static_cast 不局限于同一多态类层次中的基类和派生类,可使用static_cast调用处于不同层次的类型之间的隐式转换。
例:class B { ... }.
class D : public B { ... }.
void f(B* pb, D* pd)
{
D* pd2 = static_cast(pb). // not safe, pb may
// point to just B
B* pb2 = static_cast(pd). // safe conversion
...
}
③ reinterpret_cast 将指针类型转换为其他指针类型,将数字转换为指针或将指针转换为数字。
例: void * getmen()
{
static char buf[100].

return buf.
}

char *cp = reinterpret_cast (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 语言实现堆栈修改,通过ret跳转到自定义函数
C 类型转换运算符的使用方法
在GraphEdit中显示应用程序的Filtergraph的方法
C 私有成员变量的访问权限研究
VC 编译选项说明
防止窗口闪烁的方法
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛