例一
原网址:https://lcxing.blog.csdn.net/article/details/79521841
参考网址:https://blog.csdn.net/lin_duo/article/details/84888766
#include <iostream>
using namespace std;
class Sheep {
friend ostream& operator<<(ostream&, Sheep& sheep);
public:
Sheep(char* name, int age) {
age_ = age;
name_ = new char[strlen(name)+1];
strcpy(name_, name);
}
Sheep(const Sheep& sheep) {
age_ = sheep.age_;
name_ = new char[strlen(sheep.name_)+1];
strcpy(name_, sheep.name_);
}
~Sheep() {
if (name_ != NULL) {
delete name_;
}
}
Sheep& operator=(const Sheep& sheep) {
if (this == &sheep) {
return *this;
}
if (name_ != NULL) {
delete name_;
name_ = NULL;
}
age_ = sheep.age_;
name_ = new char[strlen(sheep.name_)+1];
strcpy(name_, sheep.name_);
}
Sheep* Clone() {
return new Sheep(*this);
}
char* GetName() {
return name_;
}
void SetName(char* name) {
if (name_ != NULL) {
delete name_;
name_ = NULL;
}
}
int GetAge() {
return age_;
}
void SetAge(int age) {
age_ = age;
}
private:
char *name_;
int age_;
};
ostream& operator<<(ostream&, Sheep& sheep) {
cout << "[name = " << sheep.name_<< ", age = " << sheep.age_ << "]";
return cout;
}
int main() {
Sheep* sheep1 = new Sheep("douli", 0);
Sheep* sheep2 = sheep1->Clone();
cout<<"sheep1:"<<*sheep1<<endl;
cout << "sheep2:" << *sheep2 << endl;
cout << "shanchu clone yuanxin sheep1" << endl;
delete sheep1;
cout << "sheep2:" << *sheep2 << endl;
return 0;
}
运行结果:
sheep1:[name = douli, age = 0]
sheep2:[name = douli, age = 0]
shanchu clone yuanxin sheep1
sheep2:[name = douli, age = 0]
留意:
ostream& operator<<(ostream&, Sheep& sheep)
例二:
原网址:https://blog.csdn.net/CoderAldrich/article/details/83115203
#include <iostream>
using namespace std;
//接口
class Prototype {
public:
Prototype() {}
virtual ~Prototype() {}
virtual Prototype * Clone() = 0;
};
//实现
class ConcretePrototype : public Prototype {
public:
ConcretePrototype():counter_(0) {}
virtual ~ConcretePrototype() {}
//拷贝构造函数
ConcretePrototype(const ConcretePrototype& rhs) {
counter_ = rhs.counter_;
}
//复制自身
virtual ConcretePrototype * Clone(){
//调用拷贝构造函数
return new ConcretePrototype (*this );
}
int counter_;
};
int main(){
//生成对像
ConcretePrototype * conProA = new ConcretePrototype ();
//复制自身
ConcretePrototype * conProB = conProA->Clone();
cout << conProB->counter_ << endl;
conProB->counter_ = 1;
cout << conProB->counter_ << endl;
delete conProA;
conProA = NULL ;
delete conProB;
conProB = NULL ;
return 0;
}
运行结果:
0
1