Virtual functions and polymorphism

后端 未结 6 1116
一向
一向 2021-01-24 00:33

Suppose I have this:

class A
{
    public:
    virtual int hello(A a);
};

class B : public A
{
   public:
   int hello(B b){ bla bla };
};

So,

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-24 01:04

    Thansk for the answers, but I have to clarify some things to get my final answer.

    Suppose I have the A class exactly how I defined it in the original question. And I add another method:

    class A {
        ...
        int yeah();
    }
    

    Then I define class B as the following:

    class B : public A {
        int hello(A a);
    };
    

    And another class C analogous to B.

    What I know because I'm the programmer, it's that the hello methods of B and C are gonna have obviously A type objects as parameters, but instances of the same class. In example:

    B b; 
    b.hello(some_other_b_instance);
    

    or

    C c; 
    c.hello(some_other_c_instance);
    

    The problem is that in each hello function of the classes B and C, I want to do particular things with atributes of the particular class B or C. And because of the parameter is of type A, I cannot use them.

    What I would need it's a kind of inverse polymorphysm, but its wrong because by definition I can send a C instance to B hello class, but I know it's not gonna happend.

    I hope you get the idea of the code... A clase is abstract, and the real work makes sense in the particular clases B and C, each one do the work in their particular way to make the yeah function work. But B and C need to access their members to do the hello work correctly.

提交回复
热议问题