简体   繁体   English

C和C++中void指针的区别

[英]Difference between void pointers in C and C++

Why the following is wrong in C++ (But valid in C)为什么以下在 C++ 中是错误的(但在 C 中有效)

void*p;
char*s;
p=s;
s=p; //this is wrong ,should do s=(char*)p;

Why do I need the casting,as p now contains address of char pointer and s is also char pointer?为什么我需要转换,因为p现在包含char指针的地址,而s也是char指针?

That's valid C, but not C++;这是有效的 C,但不是 C++; they are two different languages, even if they do have many features in common.它们是两种不同的语言,即使它们确实有许多共同点。

In C++, there is no implicit conversion from void* to a typed pointer, so you need a cast.在 C++ 中,没有从void*到类型指针的隐式转换,因此您需要进行强制转换。 You should prefer a C++ cast, since they restrict which conversions are allowed and so help to prevent mistakes:您应该更喜欢 C++ 转换,因为它们限制了允许的转换,因此有助于防止错误:

s = static_cast<char*>(p);

Better still, you should use polymorphic techniques (such as abstract base classes or templates) to avoid the need to use untyped pointers in the first place;更好的是,您应该首先使用多态技术(例如抽象基类或模板)来避免使用无类型指针; but that's rather beyond the scope of this question.但这超出了这个问题的范围。

The value doesn't matter, the type does.值不重要,类型重要。 Since p is a void pointer and s a char pointer, you have to cast, even if they have the same value.由于p是空指针而s是 char 指针,因此您必须进行强制转换,即使它们具有相同的值。 In C it will be ok, void* is the generic pointer, but this is incorrect in C++.在 C 中没问题, void*是通用指针,但在 C++ 中这是不正确的。

By the way, p doesn't contains char pointer , it's a void pointer and it contains a memory address.顺便说一下, p包含 char 指针,它是一个空指针,它包含一个内存地址。

In general, this rule doesn't even have anything to do with pointers.一般来说,这条规则甚至与指针没有任何关系。 It's just that you can assign values of some type to variables of other types, but not always vice versa.只是您可以将某种类型的值分配给其他类型的变量,但并非总是相反。 A similar situation would be this:类似的情况是这样的:

double d = 0.0;
int i = 0;

d = i;    // Totally OK
i = d;    // Warning!

So that's just something you have to live with.所以这只是你必须忍受的东西。

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

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