C++ 中的虚拷贝构造函数
在深入探讨主题之前,让我们复习一下所有相关的术语。
拷贝构造函数是一种特殊的构造函数,用于创建与传递的对象完全相同的对象。
虚函数是在父类中声明并在继承父类的子类中重新定义(重写)的成员函数。
通过使用虚拷贝构造函数,程序员能够在不知道对象确切数据类型的情况下创建对象。
在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP