Difference between void pointers in C and C++

前端 未结 3 1606
天涯浪人
天涯浪人 2020-12-19 17:46

Why the following is wrong in C++ (But valid in C)

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

Why do I need the casti

3条回答
  •  借酒劲吻你
    2020-12-19 18:02

    That's valid C, but not 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. You should prefer a C++ cast, since they restrict which conversions are allowed and so help to prevent mistakes:

    s = static_cast(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.

提交回复
热议问题