如何通过指针的类指针访问类的成员函数

How can i access member functions of a class via Class pointer of pointer?

本文关键字:指针 函数 成员 访问 何通过      更新时间:2023-10-16

下面是我的C++代码,我在下面的代码中注释掉了我的问题:

#include <iostream>
using namespace std;
class Base{
public:
    virtual void f1(){
    cout << "f1 from basen"; }
   virtual void f2(){
   cout << "f2 from basen";
 }
};
class D1: public Base {
public:
 virtual void f1(){
cout << "f1 from D1n";
}
};
class D2: public Base {
public:
 virtual void f2(){
cout << "f2 from D2n";
}
};

int main(){
Base* b1 = new D1;
b1->f1();
b1->f2();
delete b1;
Base* b2 = new D2;
b2->f1();
b2->f2();
Base** ptr = &b2;
// here how to use member function
// of b2

return 0;
}

我想通过指针访问f1() D1类的功能ptr。我已经声明了Base**并为其分配了b2。其中b2Base*类的指针。

您必须尊重Base**一次,以便可以通过指针基类调用函数。

一种可能的方法是写

(*ptr)->f1();