【发布时间】:2018-05-07 14:52:57
【问题描述】:
我不得不更改函数getData() 的原型,这基本上是一个遗留源代码。在将其从返回char* 更改为如下所示时,由于static_cast,我开始出现编译错误。我的问题是,使用reinterpret_cast 是否安全,而不是static_cast?
class C1{
public:
//void *getData() {return data;} //Legacy implementation*
char *getData() {return data;} //My new implementation
private:
char data[100];
};
int main()
{
C1 myobj;
unsigned char* begin;
begin=static_cast<unsigned char*>(myobj.getData()); *//<== This gives compile error.use reinterpret_cast ?*
return 0;
}
有比 reinterpret_cast 更好的解决方案吗?
【问题讨论】:
-
为什么
begin不是char*? -
错误信息是什么?
-
嗯,这就是他们现在拥有的方式......他们还将其转换为 char * 甚至其他不同的类型,如结构等。
-
@deep_rugs 如果
getData()应该返回一些无类型的缓冲区,调用者确定它的解释方式,我认为您将getData()更改为返回char *是错误的,应该将其改回返回void *。
标签: c++