因此,我对C ++中的复制构造函数感到困惑。我有以下代码:
class creature /* abstract class*/
{
private:
string name;
int longevity;
creature_society * cs;
public:
creature(int,int,int,creature_society*);
//creature(const creature&);
virtual ~creature();
virtual int is_a_good() =0;
};
class good_creature : public creature
{
public:
good_creature(int,int,creature_society*);
//good_creature(const good_creature&);
~good_creature();
int is_a_good() //returns 1
};
class bad_creature : public creature
{
public:
bad_creature(int,int,creature_society*);
//bad_creature(const bad_creature&);
~bad_creature();
int is_a_good(void); //returns 0
}
因此,我有一个名为
creature
的抽象类,一个 good_creature
和一个 bad_creature
,它们是 creature
的子类。在我的程序中,我还有一个名为
society
的数组,该数组的类型为creature*
。如果通过条件将我的生物定义为良好,我会为其分配空间并将其存储为society
到good_creature
数组中。坏生物也是如此。我按照以下代码中的说明构造它:society = new creature*[M];
for(i=0;i<M;i++)
{
if(condition)
society[i] = new good_creature(L,good,this);
else
society[i] = new bad_creature(L,bad,this);
}
因此,我必须制作一个纯虚函数:
creature::clone(int position)
,如果它是good_creature
或bad_creature
,它必须删除society[pos]
并通过复制构造函数复制society[pos-1]
。例如,我的
good_creature::clone(int position)
是这样的: void good_creature::clone(int position)
{
int cop_pos=position -1; //getting the position before that in order to copy it
delete society[pos];
society[pos] = new good_creature( *society[cop_pos] );
//....
}
我收到一个错误,因为
society[cop_pos]
是creature*
类型。我尝试将其投放到好生物上,但不幸的是,我不断出错。是因为我没有正确调用复制构造函数,还是因为我没有正确转换?有任何想法吗?这让我感到疲倦了2天。请记住,我是新手,可能做错了什么。另外,我不需要定义自己的副本构造函数,因为
society[i]
中的所有元素都指向creature_society * cs
定义的同一对象,所以我尝试使用默认的构造函数,因为我不需要深度复制。谢谢你的时间。
更新
我忘记提及的课程以及我建立社会的方式
class creature_society
{
private:
int N; // number of the creatures we want to be made in society
creature ** society;
public:
creature_society(int,int);
~creature_society();
};
最佳答案
您不知道society[cop_pos]
是否是正确的类型,因此无法安全地进行强制转换。更好的解决方案是使用虚函数创建副本
class creature {
public:
virtual creature* clone() const = 0;
...
};
class good_creature {
public:
good_creature* clone() { return new good_creature(*this); }
...
};
//Similar for bad_creature (and any other derived classes)
在您的情况下,您可以这样称呼它:
society[pos] = society[cur_pos]->clone();
无需知道您要克隆的对象的类型。虚函数调用将为您解决这一问题。请注意,
good_creature::clone
返回一个good_creature*
而不是creature*
。这是有效的重载。允许虚函数重载返回派生类。在这种情况下,您也可以让它返回creature*
。