请高手帮我看看这个指针数组出什么问题了?
class Parent{
public:
Parent(int a)
{
this->a = a;
}
virtual void print()
{
cout << "Parent::print a = " << a << endl;
}
int a;
};
class Child :public Parent
{
public:
Child(int a) :Parent(a)
{
}
virtual void print()
{
cout << "Child::print a = " << a << endl;
}
int b;
};
int main(void)
{
Child** pChildArray = new Child*;
for (int i = 0; i < 3; i++){
pChildArray = new Child(i);
}
Child *cp;
int i;
for (cp = pChildArray, i = 0; i < 3; i++, cp++){
cp->print();
}
for (int i = 0; i < 3; i++)
{
delete pChildArray;
}
delete[] pChildArray;
return 0;
}
子类指针cp++后怎么不能输出下一个子类对象?怎么回事? for (cp = pChildArray, i = 0; i < 3; i++, cp=pChildArray) {
cp->print();
} q30416657 发表于 2017-12-26 12:14
for (cp = pChildArray, i = 0; i < 3; i++, cp=pChildArray) {
cp->print();
}
谢谢,为什么cp++不行呢?我是照着下面这段代码改写的:
class Parent
{
public:
Parent(int a)
{
this->a = a;
}
virtual void print()
{
cout << "Parent::print a = " << a << endl;
}
int a;
};
class Child :public Parent
{
public:
Child(int a) :Parent(a)
{
}
virtual void print()
{
cout << "Child::print a = " << a << endl;
}
int b;
};
int main(void)
{
Child array[] = { Child(0), Child(1), Child(2) };
Child *cp;
int i;
for (cp = &array, i = 0; i < 3; i++, cp++){
cp->print();
}
return 0;
}
jessylake 发表于 2017-12-26 12:35
谢谢,为什么cp++不行呢?我是照着下面这段代码改写的:
class Parent
{
想明白了,这个子类指针指向的是数组中连续排列的子类对象,这里指针步长就是 sizeof(Child) ,正好可以通过++访问每个数组成员,而指针数组中每个元素的值是在堆中开辟的放置子类对象的空间的首地址,这些首地址并非像数组元素那样按照数组元素的大小连续排列的,所以按照子类指针的步长就出错误了
页:
[1]