#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 a = 0, int b = 0) :Parent(a)
{
this->b = b;
}
virtual void print()
{
cout << "我是儿子" << endl;
}
private:
int b;
};
void print(Parent *base)
{
base->print();
}
int 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();
pP++;
pC++;
return 0;
}
/*
结论:
只要子类中 多了一个属性 两个步长就不一致了
通过指针的移动去查找内容是不行的了
*/C++中父子类中指针的步长问题
最新推荐文章于 2026-06-09 20:07:16 发布
本文通过C++代码示例介绍了类的继承与多态特性,展示了基类与派生类之间的关系及如何使用多态进行函数调用。特别关注了派生类对象通过基类指针调用时的行为差异。

307

被折叠的 条评论
为什么被折叠?



