父类指针的步长和子类指针的步长是不一样的

当用父类指针或者引用指向子类对象时,可以发生多态(是因为有vptr指针和虚函数表的存在),但是这个指针和子类指针的步长时不一样,具体看如下代码,特别注意看注释。

代码如下:

#include <iostream>
using namespace std;

//结论:
//多态是用父类指针指向子类对象 和 父类步长++,是两个不同的概念

class Parent
{
public:
	Parent(int a = 0)
	{
		this->a = a;
	}

	virtual void print()
	{
		cout << "我是爹" << endl;
	}

private:
	int a;
};


//成功 ,一次偶然的成功 ,必然的失败更可怕
class Child : public Parent
{
public:
	

	Child(int b = 0) :Parent(0)
	{
		this->b = b;
	}


	virtual void print()
	{
		cout << "我是儿子" << endl;
	}
private:
	int b;
};

void HowToPlay(Parent* base)
{
	base->print(); //有多态发生  //2 动手脚  

}

void main()
{

	Child  c1; //定义一个子类对象
	Parent* pP = NULL;
	Child* pC = NULL;

	Child  array[] = { Child(1), Child(2), Child(3) };
	pP = array;
	pC = array;

	pP->print();
	pC->print(); //多态发生

	pP++;
	pC++;
	//pP->print();  执行这句话会报错,父类指针和子类指针是不一样的
	pC->print(); //多态发生

	cout << "hello..." << endl;
	system("pause");
	return;
}
发布了228 篇原创文章 · 获赞 85 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/tianguiyuyu/article/details/104570559