简体   繁体   English

在C ++中使用正确的方法

[英]Casting the proper way in C++

I apologise if this isn't considered a good enough question (since my own solution just works, so I don't actually have a problem), but here goes. 如果这不被认为是一个足够好的问题我会道歉(因为我自己的解决方案正常,所以我实际上没有问题),但是这里有。
I mean, I was brought up on C and I only learned C++ later, so maybe I'm biased, but still. 我的意思是,我在C上长大,后来才学会了C ++,所以也许我有偏见,但仍然。

In this particular case, there is one library that returns a const char* , while another library needs a void* as input. 在这种特殊情况下,有一个库返回一个const char* ,而另一个库需要一个void*作为输入。 So if I want to call the second library with the result of the first, I will need to write 因此,如果我想用第一个库的结果调用第二个库,我将需要编写

second(const_cast<void*>(static_cast<const void*>(first())));

Right? 对? That's the only proper way, right? 那是唯一合适的方式,对吧?

A char* can be implicitly converted to a void* , so your code can be simplified to this: char*可以隐式转换为void* ,因此您的代码可以简化为:

second(const_cast<char*>(first()));

This is only safe if the definition of second operates as if its parameter had the type const void* . 这是,如果定义唯一安全的second 仿佛它的参数有类型工作的const void*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM