I have class with two fields witch are pointers to abstract class. How i can write copy constructor witch will copy the data pointed with the two pointers.
Here is the class
class OSGFMenu;
class OSGFMenuItem;
typedef void(OSGFMenu::*OSGFMenuCommand)(OSGFMenuItem*);
typedef int (OSGFMenuItem::*FNMETHOD) ( int, char* );
class OSGFMenuItem:
public OSGFDrawableComponent
{
public:
OSGFMenuItem(Game& game,OSGFMenu& menu)
:OSGFDrawableComponent(game),mMenu(menu),mActive(false)
{
}
OSGFMenuItem(const OSGFMenuItem& menuItem)
:OSGFDrawableComponent(menuItem),mMenu(menuItem.mMenu)
{
Copy(menuItem);
}
OSGFMenuItem& operator=(const OSGFMenuItem& menuItem)
{
if(&menuItem != this)
Copy(me开发者_运维知识库nuItem);
return *this;
}
void SetActive(bool active)
{
mActive = active;
}
void Activate()
{
SetActive(true);
}
void DeActivate()
{
SetActive(false);
}
void SetCommand(OSGFMenuCommand command)
{
mCommand = command;
}
virtual void Render()const
{
if(!mActive)
DrawIfNotNull(mDrawData);
else
if(!DrawIfNotNull(mActiveDrawData))
DrawIfNotNull(mDrawData);
}
virtual void Update(double dTime)
{
OSGFDrawableComponent* drawData =
dynamic_cast<OSGFDrawableComponent*>(mDrawData);
if(drawData)
drawData->Update(dTime);
}
void Invoke()
{
(mMenu.*mCommand)(this);
}
~OSGFMenuItem()
{
SafeDelete(mDrawData);
SafeDelete(mActiveDrawData);
}
protected:
void SetDrawData(IDrawable* drawData)
{
mDrawData = drawData;
}
void SetActiveDrawData(IDrawable* drawData)
{
mActiveDrawData = drawData;
}
private:
bool DrawIfNotNull(IDrawable* drawData)const
{
if(!drawData)return false;
drawData->Render();
return true;
}
void Copy(const OSGFMenuItem& menuItem)
{
mCommand = menuItem.mCommand;
*mDrawData = *menuItem.mDrawData;
*mActiveDrawData = *menuItem.mActiveDrawData;
mActive = menuItem.mActive;
}
OSGFMenuCommand mCommand;
OSGFMenu& mMenu;
IDrawable* mDrawData;
IDrawable* mActiveDrawData;
bool mActive;
};
The question is whether the objects pointed by the polymorphic pointers have to be copied. If that is the case, the best option would be providing a clone()
virtual method in your contained class hierarchy that will create a copy of the object.
struct base {
virtual base* clone() = 0;
virtual void foo() = 0;
};
struct derived : base {
virtual derived* clone() { return new derived(*this); }
virtual foo();
};
class container {
base * ptr;
public:
container( base * p ) : ptr(p) {}
container( container const & lhs ) : ptr( lhs.ptr->clone() )
{}
};
If you need to copy the exact type of the IDrawable hierarchy, I think your only chance is to add a Clone()
abstract method to IDrawable interface.
Its signature will be
IDrawable* clone() const;
you may omit const
if it needs to modify the object pointed by this
.
You need a virtual copy constructor to achieve this. Since it is not supported in C++ you can simulate this effect by having a virtual clone
method. See What is a "virtual" constructor? for details.
Your IDrawable will need some sort of virtual Clone() function.
精彩评论