需求:希望某些类提供拷贝自身对象的功能,实现如下
template <typename T>
class A
{
public:
T *clone() {
return new T(static_cast<T &>(*this));
}
private:
friend T;
A() = default;
};
class B : public A<B>
{
public:
B(int value) { m_value = value; }
B(const B &other) {
m_value = other.m_value;
std::cout << "B(const B &other)" << std::endl;
}
void setValue(int value) { m_value = value; }
int getValue() { return m_value; }
private:
int m_value;
};
int main()
{
B *b1 = new B(1);
B *b2 = b1->clone();
std::cout << b2->getValue() << std::endl;
system("pause");
return 0;
}