C++给我们提供了多态,可以使得同样类型的变量,调用同样的方法,却产生完全不同的行为;但在使用多态时需要指针步长的问题。防止因为步长而出现问题。
下面我们通道一个案例说明C++指针步长问题,其实只要稍微留意就可以避免此问题,并不是难点,而是在编码时需要留意即可。
#include <iostream>
using namespace std;
class Parent{
public:
Parent(int a = 0){
this->a = a;
}
virtual void print(){
cout << "i am parent" << endl;
}
private:
int a;
};
class Child : public Parent{
public:
Child(int b = 0) :Parent(0){
this->b = b;
}
virtual void print(){
cout << "i am child" << endl;
}
private:
int b;
};
void main(){
Child c1;
Parent *pP = NULL;
Child *pC = NULL;
Child array[] = { Child(1), Child(2) };
pP = array;
pC = array;
pP->print(); #1
pC->print();
pP++;
pC++;
pP->print(); #2
pC->print();
system("pause");
return;
}
细心的朋友可能已经发现上面代码的问题了,代码在运行到“#2”出会产生错误,为什么?
因为此时父类和子类的大小不同,而指针是根据对象大小进行步长操作的,本例中父类对象比子类小,父类指针指向了子类对象,父类指针自加操作时并不能指到下一个子类对象中,此时如果调用子类的方法便会出错。