开发者

How to re-type pointer to a class and be able to reach classes functions based on it's type?

I'm writing a C++ code which should populate a screen (and it's behaviour) based on a function from the object pointer was initiated with. Let's better show it on a code:

class A:parentClass {
public:
    int X () {return 5;}
}

class B:parentClass {
public:
    int X () {return 3;}
}

class C:parentClass {
public:
    int X () {return 1;}
}

main {
    parentClass *p;
    p = new A;
    printf("%d\n,p.x); //to return 5
    delete p;
    p = new B;
    printf("%d\n,p.x); //to return 3
}

I'm getting something like this on compilation:

‘class parrentClass’ has no member named ‘x’

I know that this is wrong, as parrentClass simpl开发者_运维技巧y doesn't have that member, but I don't have an idea how to solve this. I tried to go through templates, but I'm not getting anywhere.

I also tried to replace "parentClass *p;" with "int *p;", but then I'm getting:

cannot convert ‘CardsFrame*’ to ‘int*’ 

Thanks for your suggestions in advance,

Jan


You need to declare the X() method virtual on the parent class for this to work:

class ParentClass
{
    public:
        virtual int X();
};

To be clear: the following is a complete working example (compiled with gcc):

#include <iostream>

class ParentClass {
public:
    virtual int x() = 0;
};

class A : public ParentClass {
public:
    int x() { return 5; }
};

class B : public ParentClass {
public:
    int x() { return 3; }
};

class C : public ParentClass {
public:
    int x() { return 1; }
};

int main() {
    ParentClass *p;
    p = new A;
    std::cout << p->x() << std::endl; // prints 5
    delete p;
    p = new B;
    std::cout << p->x() << std::endl; // prints 3
    delete p;
}


You really need to get your basics right as your syntax is all wrong. You need to use p->X() to call the function. And to answer the actual question make X() virtual in the base class.


printf("%d\n,p.x); //to return 5

should be:

printf("%d\n,p->X()); //to return 5

Also, X() should be virtual in the Base class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜