2010-11-27 5 views
0

그래서 내가 있다고 가정호출 상위 클래스 멤버 C++

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의 메소드를 가상으로 변경 했으므로 실행 레벨을 명시 적으로 정의 할 수있는 방법이 있습니까?

답변

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! 
+0

은 당신이 게시 것처럼 내 편집을 기록했다. 네가 한 일이 내가 필요한 것임을 믿는다. 감사 – Fuller

3

나는 DoSomething 가상을 선언하고이를 objToLookFor.DoSomething()이라고 부릅니다.

그런데 RemoveObjectFromListOrSomethingSimiliar은 아마도 A이 아니라 A*을 매개 변수로 허용해야합니다.

관련 문제