Sign-up....

请问一个强制类型转换的问题

变量定义:CObArray *poaLines

希望强制类型装换成(CLine*)poaLines[liPos]以便调用自己编写的类中的函数Draw(),

可是我这样用:((CLine*)poaLines[liPos])->Draw(pDC); 总是编译错误,请问该怎么转换

编译错误提示:

error C2440: 'type cast' : cannot convert from 'class CObArray' to 'class CLine *'

No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

[368 byte] By [msdn] at [2007-8-14 13:02:48]
# 1 Re: 请问一个强制类型转换的问题

自己实现类型转换

WingForce at 2005-5-12 22:05:53 >
# 2 Re: 请问一个强制类型转换的问题

试一下,用点(.)代箭头(->)

看能不能行的通

iangenius at 2005-5-12 22:20:30 >
# 3 Re: 请问一个强制类型转换的问题

把你自己的类继承自CObArray能不能满足要求.

llmsn at 2005-5-12 22:41:53 >
# 4 Re: 请问一个强制类型转换的问题

同意自己实现类型转换

zhaoliang_chen at 2005-5-12 22:45:10 >
# 5 Re: 请问一个强制类型转换的问题

((CLine*)&poaLines[liPos])->Draw(pDC);

cenlmmx at 2005-5-12 22:52:17 >
# 6 Re: 请问一个强制类型转换的问题

是不是由同一个对象来继承的。没有类型转换操作。

zdy_8212 at 2005-5-12 23:16:52 >
# 7 Re: 请问一个强制类型转换的问题

or do this:

class CObArray

{

public:

operator CLine*() const

{

Your conversion code here

}

.........

}

cenlmmx at 2005-5-12 23:31:13 >
# 8 Re: 请问一个强制类型转换的问题

谢谢cenlmmx,((CLine*)&poaLines[liPos])->Draw(pDC);可以了,C++语法看来还很深,大家讨论一下为什么这样就可以了?讨论共同提高,分数我还会继续添加

yalechenfly at 2005-5-13 9:06:48 >
# 9 Re: 请问一个强制类型转换的问题

to cenlmmx:

能解释下么,学习一下

brucelee0224 at 2005-5-13 9:15:57 >
# 10 Re: 请问一个强制类型转换的问题

否则只能从指针强制转向指针(CObArray * --> CLine*),但有时这样也不安全.

cenlmmx at 2005-5-13 9:19:34 >
# 11 Re: 请问一个强制类型转换的问题

另外一种实现方法:)

CLine *pLine = dynamic_cast<CLine *>(&poaLines[liPos]);

if (pLine != NULL)

{

// OK,可以任意调用CLine的函数了

pLine->Draw(pDC);

}

alvachien at 2005-5-13 9:33:32 >
# 12 Re: 请问一个强制类型转换的问题

CLine *pLine = dynamic_cast<CLine *>(&poaLines[liPos]);

--------

CLine *pLine = reinterpret_cast<CLine *>(&poaLines[liPos]);

cenlmmx at 2005-5-13 9:41:18 >
# 13 Re: 请问一个强制类型转换的问题

已经给大家分数了,继续讨论,还继续会有分数的

yalechenfly at 2005-5-13 19:04:02 >

C/C++

All Classified