C++基类与派生类的函数调用情况

来源:互联网 发布:java的工资一般多少 编辑:程序博客网 时间:2024/05/29 17:39


在定义了基类的指针与派生类的对象,或者是派生类指针与基类的对象。

在函数调用的时候,如果该函数在基类中被定义为虚函数,那么在调用的时候看该指针(包括基类指针和派生类指针)所指向的对象,如果是派生类的对象就调用派生类中重写的函数,如果是基类的对象就调用基类中的函数。如果该函数为非虚函数,那么看该指针的类型,如果是基类的指针就调用基类中的函数,如果是派生类的指针就调用派生类中的函数。这种情况是非多态的情况,函数没有实现重写,而只是进行了覆盖。

#include "iostream"using namespace std;#include<iostream>using namespace std;class Base{public:virtual void f(float x){cout<<"Base::f(float)"<< x <<endl;}void g(float x){cout<<"Base::g(float)"<< x <<endl;}};class Derived : public Base{public:virtual void f(float x){cout<<"Derived::f(float)"<< x <<endl;   //多态、覆盖}void g(int x){cout<<"Derived::g(int)"<< x <<endl;     //隐藏}};int main(void){//定义子类的对象Derived d;// 基类的指针指向子类对象Base *pb = &d;//子类指针指向子类对象Derived *pd = &d;//虚函数,是调用所指向对象的函数pb->f(3.14f);   // Derived::f(float) 3.14pd->f(3.14f);   // Derived::f(float) 3.14// 非虚函数,根据指针属于基类或子类调用pb->g(3.14f);   // Base::g(float)  3.14pd->g(3.14f);   // Derived::g(int) 3 Base a;//定义基类的对象Derived *ptr = (Derived *)&a;//子类的指针  ptr->f(3.14f);  // Base::f(float)  3.14ptr->g(3.14f); // Derived::g(int) 3 return 0;}

0 0
原创粉丝点击