开发者

Casting double pointers of base classes

I have an Abstract class, say Animal. From this class, I have many inheriting classes, such as Cat, Dog, Mouse. I have a method that I want to be able to take pointers to pointers of these objects. So void someMethod(Animal **anAnimal);

How is this accomplished? It seems I am not able to cast upwards like this. I am trying the following:

Dog *d = new Dog(x); //some parameter x.
Animal **animal = &d;
someMethod(animal);

//where someMethod has the method signature...
void someMethod(Animal **anAnim开发者_运维问答al);

What am I doing wrong, and how can I accomplish what I'm attempting?


You need an Animal*:

Dog* d = new Dog(x);
Animal* a = d;
Animal** animal = &a;
someMethod(animal);

An Animal** can only point to an Animal*. It would be very bad if it could point to a Dog*. If it could, you could do something like this:

Dog* d = new Dog(x);
Animal** animal = &d;
*animal = new Hippopotamus();

Now d points to a Hippopotamus, which is very wrong indeed.


You need to introduce a temporary of type Animal*:

Dog *d = new Dog(x); //some parameter x.
Animal *a = d;
Animal **animal = &a;
someMethod(animal);

The reason for this is that &d is Dog**, which cannot be converted to Animal** even if Dog* can be converted to Animal*.

Normally you 'd fix this inline using something like this (warning -- does not compile!):

Dog *d = new Dog(x); //some parameter x.
Animal **animal = &(static_cast<Animal*>(d));
someMethod(animal);

However, this is not possible because the return value of static_cast is a temporary (technically, its a rvalue) so you cannot get its address. Therefore, you need the extra Animal* local to make this work.


Going to have to do a cast.

Animal **animal = (Animal **)&d;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜