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