问题描述
有人可以给我一些很好的参考网站/信息
了解何时以及为什么我会使用
1.)const_cast
不知道你为什么会这样做?
2.)reinterpret_cast。
当我转换一个时我用了一点原始到一个类,但是
希望看到其他应用程序。
是的,我已经在网上看了,但是想知道一些什么的专家
了解这一点。
非常感谢您的帮助,
John
Can someone please give me some good reference site/information for
understanding when and why I would use
1.) const_cast
Don''t know why you would do this?
2.) reinterpret_cast.
I have used this a little when I converted a primitive to a class, but
would like to see other applications.
Yes, I have looked on the web, but want to know what some of the experts
know about this.
Thanks alot for your help,
John
推荐答案
我''我需要使用它来在连接不良时插入常量
写入inte将参数视为const的rfaces,但在参数列表中没有将其限定为
const。
I''ve had need to use this to cast away constness when interfacing w/ poorly
written interfaces that treat a parameter as const, but don''t qualify it as
const in the parameter list.
您可以使用它来转换不兼容的类型,例如,
unsigned char buffer [20];
if(read_message_from_com_port(buffer))
{
double x = * reinterpret_cast< double *>(缓冲区);
// ...
}
根据经验,使用reinterpret_cast if没有隐式转换
和static_cast被编译器拒绝 - 而且你确定
它是你需要的转换。
如果你无法找到这些演员阵容的用途,那么算上你的祝福。
没有人_wants_使用它们。它们应该尽可能少地使用,但是有时你必须使用它们才能使用它们。
DW
You use it to convert between incompatible types, e.g.,
unsigned char buffer[20];
if(read_message_from_com_port(buffer))
{
double x = *reinterpret_cast<double*>(buffer);
//...
}
As a rule of thumb, use reinterpret_cast if there is no implicit conversion
and static_cast is rejected by the compiler - and you are really sure that
it''s the conversion you need.
If you are unable to find uses for these casts, then count your blessings.
No one _wants_ to use them. They should be used as little as possible, but
sometimes you have to use to use them.
DW
一个可以使用它将int,double等转换为字节流,适合
用于写入调用。
int i = 3;
cout.write(reinterpret_cast< const char *>(& i),sizeof(i));
在池分配器方案中,我们分配空间存储N个元素,比如N =
100.您可以将元素的空间视为元素或指针
t o下一个元素,前提是空格的大小是> =
指向元素的空间。
还有很多其他的域名具体例子。
One can use it to convert an int, double, etc to a stream of bytes, suitable
for a call to write.
int i = 3;
cout.write(reinterpret_cast<const char *>(&i), sizeof(i));
In pool allocator schemes, we allocate space to store N elements, say N =
100. You can treat the space of element as either an element or a pointer
to the next element, provided that the sizeof the space is >= the space of a
pointer to the element.
There are lots of other domain specific examples.
这篇关于const_cast,reinterpret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!