您如何在具有相同函数名称的派生类中调用基类的函数[重复]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

我正在尝试在派生类中使用基类中存在的相同名称调用函数。该函数仅打印类元素。例如:

class A                             // Base Class
{                                    
public:                          
     string a;
     int b;

     A(){};                         //Default Constructor                         
     A(string x,int y):a(x),b(y){}  //Parametrized Constructor
     ~A(){};                        //Destructor
     void printInfo()
     {
        cout << a << endl;
        cout << b << endl;
     };     
};

class B:public A                    // Derived Class
{                                    
public:                          
     string c;


     B(){};                         //Default Constructor                         
     B(string z):c(z){}             //Parametrized Constructor
     ~B(){};                        //Destructor
     void printInfo()
     {
        cout << a << endl;
        //I am trying to call printInfo of A inside this function
     }; 
};

因此在输出中,当我创建B的对象(比方说B example;)并尝试使用B类的printInfo()成员函数(例如:example.printInfo();)时,我将首先打印c和然后是a和b。同样,它将不限于2个类,而是具有共同的printInfo()成员函数的5个以上的类。我该如何实现?

c++ inheritance derived-class base-class
1个回答
0
投票

//我正在尝试在此函数内调用A的printInfo

class B:public A                    // Derived Class
{                                    
public:                          
     string c;


     B(){};                         //Default Constructor                         
     B(string z):c(z){}             //Parametrized Constructor
     ~B(){};                        //Destructor
     printInfo()
     {
        cout << a << endl;
        A::printInfo();  //<-- call base class version
     }; 
};
© www.soinside.com 2019 - 2024. All rights reserved.