问:如何复制多态类? [英] Q: How to copy a polymorphic class?
问题描述
--- foo.h ---
class foo
{
public:
虚拟空虚DoStuff(无效);
虚拟~foo();
};
--- bar.h ---
#include" foo.h"
class bar:public foo
{
public:
virtual void DoStuff(void);
};
--- bloggs.cpp ---
#include" foo.h"
extern void Bloggs(foo * myFoo)
{
foo * localFoo = new foo(* myFoo);
localFoo-> DoStuff();
删除localFoo;
}
--- main.cpp ---
#include" bar.h"
#include " bloggs.h"
int main(int argc,char * argv [])
{
bar myBar;
Bloggs(& myBar);
返回0;
}
在上面的代码中,在functionBloggs,localFoo是一个foo副本
由foo par构造我传入的条形参数。
而不是这个,我想复制完整的bar参数并将
结果分配给localFoo。有没有办法在没有bloggs.cpp的情况下这样做?
需要#include" bar.h"? (我想我需要一些类似于
的虚拟拷贝构造函数......)
-
Simon Elliott
http://www.ctsn.co.uk/
>
Simon Elliott写道:
(我想我需要一些类似于
虚拟拷贝构造函数...)
是:
派生*派生:: create_new()
{
返回新的Derived(* this);
}
lilburne写道:
Simon Elliott写道:
(我想我需要一些类似于
虚拟拷贝构造函数的东西......)
是的:
Derived * Derived :: create_new()
{
返回new Derived(* this);
}
当然每个派生类都会需要这个功能,并且它会在基类中需要虚拟或纯虚拟,并且它应该是
const。此外,clone()是一个更广泛使用(也更合适)的名称
。
lilburne< li ******@godzilla.net>写道(我想我需要一些类似于
虚拟拷贝构造函数的东西......)
是:
Derived * Derived :: create_new()
{
返回new Derived(* this);
}
>
非常好。这将很好地完成工作。
-
Simon Elliott
http://www.ctsn.co.uk/
blockquote>
--- foo.h ---
class foo
{
public:
virtual void DoStuff(void);
virtual ~foo();
};
--- bar.h ---
#include "foo.h"
class bar:public foo
{
public:
virtual void DoStuff(void);
};
--- bloggs.cpp ---
#include "foo.h"
extern void Bloggs(foo* myFoo)
{
foo* localFoo = new foo(*myFoo);
localFoo->DoStuff();
delete localFoo;
}
--- main.cpp ---
#include "bar.h"
#include "bloggs.h"
int main(int argc, char* argv[])
{
bar myBar;
Bloggs (&myBar);
return 0;
}
In the code above, In the function "Bloggs", localFoo is a foo copy
constructed from the foo part of the bar argument I passed in.
Instead of this, I want to copy the complete bar argument and assign the
result to localFoo. Is there any way of doing this without bloggs.cpp
needing to #include "bar.h"? (I suppose I need something analogous to a
virtual copy constructor...)
--
Simon Elliott
http://www.ctsn.co.uk/
解决方案Simon Elliott wrote:
(I suppose I need something analogous to a
virtual copy constructor...)
Yes:
Derived* Derived::create_new()
{
return new Derived(*this);
}
lilburne wrote:
Simon Elliott wrote:(I suppose I need something analogous to a
virtual copy constructor...)
Yes:
Derived* Derived::create_new()
{
return new Derived(*this);
}
Of course every derived class would need that function, and it would
need to be virtual or pure virtual in the base class, and it should be
const. Also, clone() is a more widely used (and more appropriate) name
for it.
lilburne <li******@godzilla.net> writes(I suppose I need something analogous to a
virtual copy constructor...)
Yes:
Derived* Derived::create_new()
{
return new Derived(*this);
}
Excellent. That will do the job nicely.
--
Simon Elliott
http://www.ctsn.co.uk/
这篇关于问:如何复制多态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!