«
C++子类对象调用父类函数

时间:2023-7-5    作者:范文泉    分类: 编程


class A
{
public:
    virtual int Add() { return 2; }
};

class B : public A
{
public:
    virtual int Add() { return 3; }
};

B *b = new B();
int a = b->Add();//3
int a = ((A*)b)->Add();//3
int a = b->A::Add();//2

//test.cc
#include <iostream>
using namespace std;
class A
{
public:
    virtual void func()
    {
        cout <<" this is A" << endl;
    }
};

class B : public A
{
public:
    virtual void func()
    {
        cout <<" this is B" << endl;
    }
};

int main()
{
    A a;
    B b;
    A* c = new B(); 
    a.func();     //this is A
    b.func();     //this is B
    b.A::func();  //this is A
    c->func();    //this is B
    c->A::func(); //this is A
    return 0;
}