为什么C ++禁止void *的隐式转换? [英] Why does c++ forbid implicit conversion of void*?

查看:838
本文介绍了为什么C ++禁止void *的隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,我们可以转换无效* 任何其他指针。

In C, we can convert void* to any other pointers.

不过,C ++禁止它。

But C++ forbids it.

int *a = malloc(4);

导致这个错误:

invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]

有没有这里的任何潜在危险,在C ++?

Are there any latent dangers here in c++?

是C的有什么例子++?

Are there any examples of c++?

推荐答案

在C ++中,不像在C,你的有无以的投malloc的结果。您code可以调整到一个简单的投工作秩序。

In C++, unlike in C, you have to cast the result of malloc. Your code can be tweaked into working order with a simple cast.

int *a = (int *)malloc(4);

这个强制性蒙上了伟大的文章,它的可以在这里找到。 结果
一个额外的链接,以供参考可以在这里找到。

编辑:正如意见建议,使用的malloc()不应该是司空见惯。最近的另一种方法是使用分配。

As suggested in the comments, the use of malloc() should not be commonplace. The closest alternative is using new to allocate.

int *a = new int[15];

其他编辑:如再次提出的意见,如果你必须使用的malloc(),至少使用C ++投<。 / p>

Additional As again suggested in the comments, if you have to use malloc(), at least use a C++ cast.

int *a = static_cast<int*>malloc(sizeof(int)); // shout out to @edheal, @mgetz

这篇关于为什么C ++禁止void *的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆