(待改進...)
class ShallowCopyPrototype : public Prototype {
public:
int* data;
ShallowCopyPrototype() {
data = new int;
}
std::unique_ptr<Prototype> clone() const override {
auto cloneObj = std::make_unique<ShallowCopyPrototype>();
cloneObj->data = this->data; // 只拷貝指針,不拷貝指針指向的數據
return cloneObj;
}
};
缺點
class DeepCopyPrototype : public Prototype {
public:
int* data;
DeepCopyPrototype() {
data = new int;
}
std::unique_ptr<Prototype> clone() const override {
auto cloneObj = std::make_unique<DeepCopyPrototype>();
cloneObj->data = new int; // 創建新的內存
*(cloneObj->data) = *(this->data); // 拷貝數據
return cloneObj;
}
};
優點
ClassName(const ClassName& other);
class MyClass {
private:
int* data;
public:
// 普通構造函數
MyClass(int value) {
data = new int(value);
}
// 拷貝構造函數(深拷貝)
MyClass(const MyClass& other) {
data = new int(*other.data);
}
// 解構函數
~MyClass() {
delete data;
}
void show() {
std::cout << *data << std::endl;
}
};
int main() {
MyClass obj1(42);
MyClass obj2 = obj1; // 調用拷貝構造函數
obj1.show(); // 輸出:42
obj2.show(); // 輸出:42
}
// 原型基類
class Prototype {
public:
virtual std::unique_ptr<Prototype> clone() const = 0;
virtual void operation() const = 0;
};
// 具體原型
class ConcretePrototype : public Prototype {
public:
std::unique_ptr<Prototype> clone() const override {
return std::make_unique<ConcretePrototype>(*this);
}
void operation() const override {
std::cout << "ConcretePrototype operation" << std::endl;
}
};
int main() {
std::unique_ptr<Prototype> prototype = std::make_unique<ConcretePrototype>();
prototype->operation();
std::unique_ptr<Prototype> clonedPrototype = prototype->clone();
clonedPrototype->operation();
}