C++深拷贝(含有子类数据的)父类指针到新的父类指针

#include 
#include 

using namespace std;
class A
{
public:
	A() { cout << "A()" << endl; };
	virtual ~A() { cout << "~A()" << endl; };
	int a;
	string b;
};

class B : public A
{
public:
	B() { cout << "B()" << endl; c = "789"; };
	B(B* Bb) { *this = *Bb; }
	B(A* Bb) { B* bb = dynamic_cast(Bb); *this = *bb; }
	~B() { cout << "~B()" << endl; };
	string c;
};

int main()
{
	using namespace std;

	//模拟数据,给到父类指针 a0 有子类的数据,它们共用一个地址
	B* b0 = new B;
	b0->c = "fyu";
	b0->a = 432;
	b0->b = "fsa";
	A* a0 = b0;

	//深拷贝父类指针 a0 的数据到新的父类指针 a1 中
	A* a1 = new B(a0);

	if (b0) { delete b0; b0 = nullptr; }
	if (a1) { delete a1; a1 = nullptr; }
	if (a0) { a0 = nullptr; }//a0与b0共用一个地址,只需要赋空,不需要delete
	
	return 0;
}

你可能感兴趣的:(c++,开发语言)