Running code link 我有一个对象IObject的基类,从中创建了2个派生类derivedObject和derivedObject2。我有一个IAlgoInterace基本实现的print,它接受IObject,然后我从IAlgoInterace派生的derivedAlgo来自同一个。派生类derivedAlgo使用派生类derivedObject&的参数覆盖print方法。 derivedObject 2。当我使用print函数打印对象时,它将进入基类。
为什么我的派生类的正确打印被调用? 如何不改变基础IAlgoInterace并仍然实现此功能
目标:实现策略设计模式和粘贴在这里的代码是一个小的可执行部分。我的目标是,基本类IAlgoInterace永远不需要提供更多信息,而不是它具有可以采用所有不同类型的派生类对象的打印。实际实现,即在派生算法中,将基于传递给它的派生对象。派生算法中的print将使用来自其中的正确对象的数据元素。
因此,derivedAlgo类将打印derivedObject2,与来自derivedAlgo2类
的方式不同#include "stdafx.h"
#include "iostream"
using namespace std;
class IObject
{
public:
int data;
};
class derivedObject: public IObject
{
public:
int dataAdditonal;
};
class derivedObject2: public IObject
{
public:
int dataAdditonal;
};
class IAlgoInterace
{
public:
virtual void print(IObject * object)
{
cout << "\n base algo called";
}
};
class derivedAlgo : public IAlgoInterace
{
public:
virtual void print(derivedObject * object)
{
cout << "\n derived called for objct type 1 " ;
}
virtual void print(derivedObject2 * object)
{
cout << "\n derived called for object type 2 " ;
}
};
class derivedAlgo2 : public IAlgoInterace
{
public:
virtual void print(derivedObject * object)
{
cout << "\n derived algo2 called for objct type 1 " ;
}
virtual void print(derivedObject2 * object)
{
cout << "\n derived algo2 called for object type 2 " ;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
IObject * object = new derivedObject();
IObject * object2 = new derivedObject2();
IAlgoInterace * algo = new derivedAlgo();
algo->print(object);
algo->print(object2);
int y ;
cin >> y;
}