C/C++指针常见问题随记1(类指针使用出现崩溃问题)

今天在论坛上看见了如下这么一段代码,让我想起了当初学习指针时候也常出错,所谓,眼过千遍,不如手过一遍,故,博客一篇以记之。

题主的问题是://引发多态2,代码崩溃了,为什么?

#include <iostream>
using namespace std;
class Parent {
public:
	Parent(int a = 0) {
		this->a = a;
	}
	virtual void print() {
		cout << "Parent" << endl;
	}
private:
	int a;
};

class Child : public Parent {
public:
	Child(int b = 0) :Parent(0) {
		this->b = b;
	}
	virtual void print() {
		cout << "Child:" << b << endl;
	}
private:
	int b;
};

int main() {
	Parent* pP = NULL;
	Child* pC = NULL;
	Child array[] = { Child(1), Child(2), Child(3) };
	pP = array;
	pC = array;
	pP->print();//引发多态1
	pC->print();
	pP ++;
	pC ++;
	pP->print();//引发多态2
	pC->print();

	return 0;
}

 C/C++指针常见问题随记1(类指针使用出现崩溃问题)