[MFC学习之C++基础] 孙鑫视频中第三讲中提到的小测试程序(关于基类和子类的继承关系)
根据他的意思写了小程序如下:
//孙鑫视频中第三课中提到的小测试程序例子
#include <iostream.h>
class Animal
{
public:
Animal()
{
// TODO: add construction code here
//cout<<"Animal construct"<<endl;
m_panimal = this;
}
~Animal()
{
// TODO:add deconstruction code here
//cout<<"Animal deconstruc"<<endl;
}
Animal* getp()
{
return m_panimal;
}
virtual void test()
{
cout<<"Animal::test"<<endl;
}
private:
Animal *m_panimal;
};
class Fish:public Animal
{
public:
Fish()
{
// TODO: add construction code here
//cout<<"Fish construct"<<endl;
}
~Fish()
{
// TODO:add deconstruction code here
//cout<<"Fish deconstruct"<<endl;
}
void test()
{
cout<<"Fish::test"<<endl;
}
};
int main()
{
Fish myfish;
Animal animal;
Animal* p1 = myfish.getp();
Animal* p2 = animal.getp();
p1->test();
p2->test();
return 0;
}
#include <iostream.h>
class Animal
{
public:
Animal()
{
// TODO: add construction code here
//cout<<"Animal construct"<<endl;
m_panimal = this;
}
~Animal()
{
// TODO:add deconstruction code here
//cout<<"Animal deconstruc"<<endl;
}
Animal* getp()
{
return m_panimal;
}
virtual void test()
{
cout<<"Animal::test"<<endl;
}
private:
Animal *m_panimal;
};
class Fish:public Animal
{
public:
Fish()
{
// TODO: add construction code here
//cout<<"Fish construct"<<endl;
}
~Fish()
{
// TODO:add deconstruction code here
//cout<<"Fish deconstruct"<<endl;
}
void test()
{
cout<<"Fish::test"<<endl;
}
};
int main()
{
Fish myfish;
Animal animal;
Animal* p1 = myfish.getp();
Animal* p2 = animal.getp();
p1->test();
p2->test();
return 0;
}
当我们用myfish对象去调用getp函数时,得到的指针是Fish类对象的指针,而用animal对象去调用getp函数时,得到的指针是Animal类对象的指针。
这就可以说明问题了。
我没有什么雄心壮志,我只想给自己和关心自己的家人和朋友一个交代,仅此而已。