This commit is contained in:
xliu79
2020-07-18 23:30:56 +08:00
parent f04d7db8e9
commit 9f6088a31e
5 changed files with 144 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
/**
* @file c++_examp.cpp
* @brief c++中的多态
* @author 光城
* @version v1
* @date 2019-08-06
*/
#include <iostream>
using namespace std;
class A
{
public:
virtual void f()//Implement a virtual function
{
cout << "Base A::f() " << endl;
}
};
class B:public A // 必须为共有继承否则后面调用不到class默认为私有继承
{
public:
virtual void f()//Virtual function implementation, virtual keyword in subclass can not be appearence
{
cout << "Derived B::f() " << endl;
}
};
int main()
{
A a;//Base class object
B b;//an object of derived type
A* pa = &a;//The parent class pointer points to the parent object
pa->f();//Call the function of the parent class
pa = &b; //The parent class pointer points to the subclass object, which is implemented in polymorphism
pa->f();//Call the function with the same name of the derived class
return 0;
}