开发者

Simple Pointer Question

edit: nevermind, solved...I'd declared type in ClassB AND ClassC..开发者_运维知识库..

So I have a pointer, named PointA, in a class called ClassA.

ClassA and ClassB are both derived from ClassC, which has a variable called type.

In a section of code I assign a new instance of ClassB to ClassA's PointA variable. The pointer is declared to point to ClassC, of which ClassB is derived from.

I then have a function, in OtherClass (irrelevant), that looks a bit like this:

void OtherClass::function_name(ClassA* A,ClassB* B) {
    B->type; //displays the correct value of type

    A->PointA->type; //displays the wrong value of type
    (A->PointA)->type; //displays the wrong value of type
}

I know that PointA points correctly to the instance of ClassB.

What am I doing wrong to get the incorrect value of type when I use the pointer?


I suspect you did an illegal cast when populating PointA. ClassB needs to be a subclass of the thing that PointA is defined to point to ( typeof(*ClassA->PointA) ) or else what you are trying to do will not work.


According to your code, both ClassA and ClassB have a member named type. Since you can make your PointA point to either ClassA object or ClassB object, there must be a parent-child relationship between these classes (is there?). If so, are you sure that you did not create two completely unrelated type members: one in ClassA and another in ClassB? You expect to inspect ClassB::type, but in fact you inspect ClassA::type, which is why you see a different ("wrong") value.

You need to post more code, to show us how the classes are declared. With what you posted one can only make wild guesses... On top of that, the code you posted is obviously "fake", i.e. it is not the code you made your experiments with. The ClassA->PointA->type expression will not even compile. Post real code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜