在深入探讨主题之前,我们先梳理所有相关术语。
一个拷贝构造函数是用来创建一个对象,它是通过物体的精确拷贝构造函数的一种特殊类型。
虚函数是在父类中声明的成员函数,并在继承父类的子类中重新定义(重写)。
通过使用虚拟副本构造函数,程序员可以在不知道对象确切数据类型的情况下创建对象。
在C ++编程语言中,复制构造函数用于创建从另一个对象复制的对象。但是,如果您希望程序在运行时决定所创建对象的类型,即该对象类型是在运行时而不是在编译时定义的,并且是基于用户为特定条件提供的某些输入。在这种情况下,我们需要具有某些特殊功能的复制构造函数来执行此操作。因此,此虚拟副本构造函数被声明为提供实时对象的克隆。
让我们举个例子,假设我们有一个图,可以使用该程序找出谁是区域。但是对象的类型定义为实时,可以是正方形或圆形。因此,我们将使用虚拟副本构造函数,该构造函数将根据用户输入的类型复制对象。
为了使虚拟构造函数正常工作,在基类上定义了两个方法。他们是-
clone() create()
复制构造函数使用虚拟克隆方法,而默认构造函数使用虚拟创建方法创建虚拟构造函数。
#include <iostream>
using namespace std;
class figure{
public:
figure() { }
virtual
~figure() { }
virtual void ChangeAttributes() = 0;
static figure *Create(int id);
virtual figure *Clone() = 0;
};
class square : public figure{
public:
square(){
cout << "square created" << endl;
}
square(const square& rhs) { }
~square() { }
void ChangeAttributes(){
int a;
cout<<"The side of square";
cin>>a;
cout<<"Area of square is "<<a*a;
}
figure *Clone(){
return new square(*this);
}
};
class circle : public figure{
public:
circle(){
cout << "circle created" << endl;
}
circle(const circle& rhs) { }
~circle() { }
void ChangeAttributes(){
int r;
cout << "enter the radius of the circle ";
cin>>r;
cout<<"the area of circle is "<<((3.14)*r*r);
}
figure *Clone(){
return new circle(*this);
}
};
class rectangle : public figure{
public:
rectangle(){
cout << "rectangle created" << endl;
}
rectangle(const rectangle& rhs) { }
~rectangle() { }
void ChangeAttributes(){
int a ,b;
cout<<"The dimensions of rectangle ";
cin>>a>>b;
cout<<"Area of rectangle is "<<a*b;
}
figure*Clone(){
return new rectangle(*this);
}
};
figure *figure::Create(int id){
if( id == 1 ){
return new square;
}
else if( id == 2 ){
return new circle;
}
else{
return new rectangle;
}
}
class User{
public:
User() : figures(0){
int input;
cout << "Enter ID (1, 2 or 3): ";
cin >> input;
while( (input != 1) && (input != 2) && (input != 3) ){
cout << "Enter ID (1, 2 or 3 only): ";
cin >> input;
}
figures = figure::Create(input);
}
~User(){
if( figures ){
delete figures;
figures = 0;
}
}
void Action(){
figure *newfigure = figures->Clone();
newfigure->ChangeAttributes();
delete newfigure;
}
private:
figure *figures;
};
int main(){
User *user = new User();
user->Action();
delete user;
}输出结果
Enter ID (1, 2 or 3): 2 circle created enter the radius of the circle R 3 the area of circle is 28.26