一定要注意c++父类与子类指针步长的问题!

一、先看个错误案例

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;

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

	int a;
};
class Child :public Parent
{
public:
	Child(int a) :Parent(a)
	{

	}
	virtual void print() {
		cout << "Child::print()" << endl;
	}

	int b;
};
int main()
{
	Child array[] = { Child(0),Child(1),Child(2) };
	Parent *pp = &array[0];
#if 1
	for (int i = 0; i < 3; i++,pp++)
	{
		pp->print();
	}
#endif 
	return 0;
}

原本想让父类的指针pp每个循环进行加一,然后通过多态打印出子类中的函数,但是编译器报错!

原因分析:因为pp是父类的指针变量,pp++=pp+sizeof(Parent),也就是pp++实际上是加的4个字节,而pp指向的又是子类Child的对象地址,sizeof(Child)=8,因为它有两个int成员变量(一个继承至父类int a,一个是自己的int b),所以在array数组中,每个Child对象地址间隔是8个字节,当pp++的时候,并没有指向下一个Child对象的地址,所以编译器报错。

解决办法及注意事项:我尝试把上面#if 1与#endif中的语句进行修改,加了一行代码pp=pp+1;如下:

#if 1
	for (int i = 0; i < 3; i++,pp++)
	{
		pp->print();
		pp = pp + 1;
	}
#endif 

以为这样就可以了,但是编译器还是报错!感觉虽然是这样的,但是就是行不通,内存中寻址具体多一点或者少一点我现在无从得知,所以就不要这样做了,目前的解决办法是通过改变数组指针,如下:

int main()
{
	Child array[] = { Child(0),Child(1),Child(2) };
	Parent *pp = NULL;
#if 1
	for (int i = 0; i < 3; i++)
	{
		pp = &array[i];
		pp->print();
	}
#endif 
	return 0;
}

二、总结

一定要认识到:C、C++中的指针++或者+1,-1,都只是针对指向的数据类型的地址+1或者-1。

猜你喜欢

转载自blog.csdn.net/Topdandan/article/details/79773976