파생 클래스로는 할 수없는 일이 있습니다. 기본적으로 하나의 기본 클래스에는 상호 작용 메서드가 있으며, 다른 기본 클래스 개체를 인수로 사용합니다. 그런 다음 파생 클래스가 있고 상호 작용 메서드 - 파생 클래스 개체가 자신의 스타일로 상호 작용해야합니다 오버로드 할 싶습니다. 지금까지는 너무 좋아서 가상 메서드를 사용하여 원하는 동작을 얻었습니다. 그러나 대화 형 메서드를 오버로드하여 파생 클래스 개체를 인수로 사용할 수도 있습니다.파생 클래스로 오버로드 된 메서드 호출
이제는 baseclass 매개 변수가있는 객체가 있습니다. 매개 변수로 파생 클래스가있는 객체를 만들고 매개 변수로 파생 클래스로 만든 다른 객체와 상호 작용할 때 예상 한대로 파생 클래스의 상호 작용 메소드를 호출하지만 기본 클래스를 사용하여 메소드를 고려합니다. 매개 변수. 다른 방법을 사용하게하는 방법이 있습니까?
아래 코드는, 나는 전혀 이렇게 어쨌든이이
#include <iostream>
class BaseClass{
public:
BaseClass();
virtual ~Baseclass();
virtual void interact(BaseClass* interaction_target){std::cout << "base class interaction" << std::endl;}
};
class DerivedClass : BaseClass{
public:
DerivedClass();
virtual ~DerivedClass();
virtual void interact(BaseClass* interaction_target){std::cout << "derived class interaction" << std::endl;}
virtual void interact(DerivedClass* interaction_target){std::cout << "interaction eased by the fact that two DerivedClass object are interacting" << std::endl;}
};
class MyObject{
protected:
BaseClass* interactor;
public:
MyObject(BaseClass* param) : interactor(param){}
virtual ~MyObject();
void ObjectInteraction(MyObject interaction_target){interactor->interact(interaction_target.interactor);}
};
int main(){
MyObject first_obj(new DerivedClass());
MyObject sec_obj(new DerivedClass());
first_obj.ObjectInteraction(sec_obj); // prints derived class interactions, whereas I would like
// it to use the second method ie. interact(DerivedClass*)
return 0;
}
와 명확 있나요 희망?