我有一项要求我使用复制构造函数的作业。所以我们假设我们有以下代码:
class Animal /*abstract class*/
{
private:
string name;
int age;
public:
Animal();
~Animal();
virtual int is_bad() = 0;
}
class Dog : public Animal
{
public:
Dog();
~Dog();
int is_bad() {
return 0;
}
}
/*constructors*/
Animal::Animal(int age,string name)
{
this->age=age;
this->name=name;
}
Dog::Dog(int age, string name) : Animal(age,name)
{
cout << "Woof" << endl;
}
/*main*/
int main()
{
Animal * c;
c = new Dog(10,"rex");
return 0;
}
所以我的问题如下。如果我想创建一个复制构造函数来复制dog,例如Dog(const Dog & d)
,我需要将什么添加到我的代码中,如何在我的main函数中调用它?
我是新手,所以我需要一个非常详细的答案。
答案 0 :(得分:0)
使用Animal*
指向Dog
对象时,无法使用复制构造函数。您需要实施clone()
功能。
int main()
{
Animal * c;
c = new Dog(10,"rex");
Animal* newDog = c->clone();
return 0;
}
其中clone()
声明如下:
class Animal /*abstract class*/
{
private:
string name;
int age;
public:
Animal();
~Animal();
virtual Animal* clone() const = 0;
virtual int is_bad() = 0;
};
clone()
可以使用复制构造函数在Dog
中实现。
class Dog : public Animal
{
public:
Dog();
~Dog();
virtual Dog* clone() const { return new Dog(*this); }
int is_bad() {
return 0;
}
};
如果您有Dog*
,则可以直接使用复制构造函数。
int main()
{
Dog * c;
c = new Dog(10,"rex");
Dog* newDog = Dog(*c);
return 0;
}
答案 1 :(得分:0)
如果您没有编写复制构造函数,编译器会添加一个默认复制构造函数,复制该对象的所有成员。 在你的情况下(作业)我想你应该写一个。
要调用复制构造函数,您有两种选择:
Dog a(10, "rex");
Dog b(a); // it's calling the copy constructor
Dog c=a; // it's still calling the copy constructor
答案 2 :(得分:0)
我想要做的是通过复制构造函数创建对象Dog
的副本。我认为这是因为class Animal
是抽象 类,因为在我的作业中我在类中也有一个指针,调用默认构造函数会给我错误。但是,因为在每个Animal
中我希望它们的指针值保持不变并指向调用默认构造函数的某个对象。总而言之,我只是感到困惑,因为在调用Dog
的构造函数时,我不得不使用初始化列表来赋值,并认为同样适用于复制构造函数。感谢所有帮助的人。