开发者

Types conversion between different types in an implicit manner

开发者 https://www.devze.com 2023-03-28 02:26 出处:网络
I need an in implicit conversion from A* to C*; i cannot change A\'s definition or implementation. class A

I need an in implicit conversion from A* to C*; i cannot change A's definition or implementation.

class A
{
};

struct B: public A
{
};

struct C: public B
{

};

when i write the following:

A* p;
C* q = p;

i am getting an error C2440; cannot convert from A* to C*. what can i do giving the fact i cannot change A. both classes are plain structs of prim开发者_如何转开发itive data.


The only way you can do this is to use a cast:

// a C++ style static_cast:
C* q = static_cast<C*>(p);

// or the less verbose C-style cast
C* q = (C*)p;

Because C is a derivative of A and not every A is a C, it cannot be implicitly casted (like you could implicitly cast a C* to an A* because every C is an A (i.e. A has "less or equal features" than C, but not more)).

I doubt that you really must have an implicit cast between pointer types. What is it making you think you do?

0

精彩评论

暂无评论...
验证码 换一张
取 消