2010-11-27 2 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()? 
} 

それが意味

を行う場合、私はわからないんだけど[EDIT] [OK]を、それはちょっと働いているそう。それはまだ私を混乱させる基本方法にリダイレクトしていますが。

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*をパラメータとして受け入れる必要があります。

関連する問題