空指针:C和C ++的区别 [英] void pointers: difference between C and C++
问题描述
我想了解的问候空指针C和C ++之间的差异。在C编译如下而不是C ++(所有编译与海湾合作委员会所做/ G ++ -ansi -pedantic -Wall):
I'm trying to understand the differences between C and C++ with regards to void pointers. the following compiles in C but not C++ (all compilations done with gcc/g++ -ansi -pedantic -Wall):
int* p = malloc(sizeof(int));
由于的malloc
收益无效*
,其中C ++不允许分配到为int *
而C呢。
Because malloc
returns void*
, which C++ doesn't allow to assign to int*
while C does.
不过,在这里:
void foo(void* vptr)
{
}
int main()
{
int* p = (int*) malloc(sizeof(int));
foo(p);
return 0;
}
这两个C ++和C没有抱怨编译。为什么呢?
Both C++ and C compile it with no complain. Why?
K&放大器; R2说:
K&R2 say:
不限指针的对象可以是
转换为类型为void *无损失
的信息。如果结果是
转换回原始指针
类型,原始指针是
恢复。
Any pointer to an object may be converted to type void * without loss of information. If the result is converted back to the original pointer type, the original pointer is recovered.
这pretty资金全部有关于无效*
在C什么的C ++标准听写?
And this pretty sums all there is about void*
conversions in C. What does C++ standard dictate?
推荐答案
在C,指针转换和从无效*
总是隐含的。
In C, pointer conversions to and from void*
were always implicit.
在C ++中,从 T *
转换为无效*
是隐含的,但无效*
来什么都需要一个演员。
In C++, conversions from T*
to void*
are implicit, but void*
to anything else requires a cast.
这篇关于空指针:C和C ++的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!