C++(Base Derive)

include <iostream>

using namespace std;
class Base
{
public:
virtual void Show()
{
cout << "Base::Show()" << endl;
}
};

class Derive : public Base
{
public:
virtual void Show()
{
cout << "Derive::Show()" << endl;
}
};
void fun1(Base *ptr)
{
ptr->Show();
}
void fun2(Base &ref)
{
ref.Show();
}
void fun3(Base b)
{
b.Show();
}

int main()
{
Base b, *p = new Derive;
Derive d;
fun1(p);
fun2(b);
fun3(d);

system("pause");
return 0;

}

show()是虚函数;
*p是D对象,因此fun1(p)--》Derive;
b是B对象,因此fun2(b) --》Base;
d是D对象,B是D的父类,调用fun3(d)会将d转成B对象,因此,输出Base;
Derive::Show()
Base::Show()
Base::Show()

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容