调用上层类成员C ++

时间:2010-11-27 19:05:29

标签: c++ inheritance

假设我有:

Class A
{
void A::DoSomething();
A::A()
};

Class B : public A
{
void B::DoSomething();
B::B()
}

Class C : public A
{
void C::DoSomething();
C::C()
}

B obj1;
C obj2;

void RemoveObjectFromListOrSomethingSimiliar(A objToLookFor)
{
//assuming you found the object, how would you call the top-level DoSomething() (for example B::DoSomething() ) instead of the A::DoSomething()?
}

我不确定这是否合理

[编辑] 好的,这样有点工作。虽然它仍然重定向到基本方法,这让我感到困惑。

B obj1;
c obj2;
AList.push_back(obj1);
AList.push_back(obj2);

//later, in another method:

A objInBack = AList.back();
objInBack.DoSomething();

AList.pop_back();

objInBack引用类结构的A级,然后调用DoSomething()的级别。我已经将A的方法改为虚拟,所以有没有办法明确定义执行级别或?

2 个答案:

答案 0 :(得分:4)

我不确定我的问题是否正确,但我猜你需要的是动态绑定。

以下是基于伪代码的示例。

#include <iostream>

class A
{
    public:
        A() {}
        virtual void DoSomething() { std::cout << "A did something!" << std::endl; }
};

class B : public A
{
    public:
        B() {}
        void DoSomething() { std::cout << "B did something!" << std::endl; }
};

class C : public A
{
    public:
        C() {}
        void DoSomething() { std::cout << "C did something!" << std::endl; }
};

void DoSomethingWithSomething(A* ptr)
{
    ptr->DoSomething();
}

int main()
{
    A* obj1 = new A();
    A* obj2 = new B();
    A* obj3 = new C();
    B* obj4 = new B();
    C* obj5 = new C();

    DoSomethingWithSomething(obj1);
    DoSomethingWithSomething(obj2);
    DoSomethingWithSomething(obj3);
    DoSomethingWithSomething(obj4);
    DoSomethingWithSomething(obj5);
}

输出将是:

A did something!
B did something!
C did something!
B did something!
C did something!

答案 1 :(得分:3)

我会声明DoSomething虚拟,并将其称为objToLookFor.DoSomething()

顺便说一句,您的RemoveObjectFromListOrSomethingSimiliar可能需要接受A*作为参数,而不仅仅是A