调用基类的受保护函数时出错

Error while calling protected function of base class

本文关键字:出错 函数 受保护 基类 调用      更新时间:2023-10-16

我是C++的初学者。我正在研究继承问题。在我的代码中,当我试图从派生类调用基类的成员函数时,我会得到错误statement cannot resolve address of overloaded function。我已经应用了作用域运算符,基类的成员函数受到保护,这样派生的就不会有访问函数的问题。我在这里做错了什么?这是我的代码:

#include <iostream>
#include <string.h>
using namespace std;
class Employee
{
private:
    char *emp_name;
    int emp_code;
    char *designation;
protected:
    Employee(char *name ="",int code = 0,char *des = "", int nlength=1, int dlength=1): emp_code(code)
    {
        emp_name = new char[nlength+1];
        strncpy(emp_name,name,nlength);
        designation = new char[dlength+1];
        strncpy(designation,des,nlength);
    }
    ~Employee()
    {
        delete[] emp_name;
        delete[] designation;
    }
    char* GetName()
    {
        return emp_name;
    }
    int GetCode()
    {
        return emp_code;
    }
    char* GetDes()
    {
        return designation;
    }
};
class Work: public Employee
{
private:
    int age;
    int year_exp;
public:
    Work(char *name ="", int code = 0, char *des = "", int nlength=1, int dlength=1, int w_age=0, int w_exp=0):Employee(name,code,des,nlength,dlength),age(w_age),year_exp(w_exp)
    {
    }
    void GetName()
    {
        Employee::GetName;
    }
    void GetCode()
    {
        Employee::GetCode;
    }
    void GetDes()
    {
        Employee::GetDes;
    }
    int GetAge()
    {
        return age;
    }
    int GetExp()
    {
        return year_exp;
    }
};
int main()
{
    using namespace std;
    Work e1("Kiran",600160,"Implementation Specialist", strlen("Kiran"),strlen("Implementation Specialist"),24,5);
    cout << "Name: " << e1.GetName() << endl;
    cout << "Code: " << e1.GetCode() << endl;
    cout << "Designation: " << e1.GetDes() << endl;
    cout << "Age: " << e1.GetAge() << endl;
    cout << "Experience: " << e1.GetExp() << endl;
}

此外,我得到了错误no-match for operator<<。我不打印任何课程。我只是在这里调用派生类的函数。

如前所述,派生类Work::GetNamevoid,因此不会返回任何值。您可以将其更改为:

class Work: public Employee
{
//...
public:
//...
    char *GetName()
    {
        return Employee::GetName();
    }

或者,如果您只想重用基类Employee::GetName(),但在派生类中公开它,那么您所需要做的就是在Work中将它重新声明为public。

class Work: public Employee
{
//...
public:
//...
    using Employee::GetName; // <--- this re-declares the inherited GetName() as public


[EDIT]更改了"重新声明"代码,以遵循当前的C++最佳实践,感谢@AlanStokes的评论。具体来说,"访问声明",如最初使用的声明

    Employee::GetName; // <--- this re-declares the inherited GetName() as public

自C++98以来,一直反对使用具有相同效果的"使用声明"。

    using Employee::GetName; // <--- this re-declares the inherited GetName() as public

C++不允许引用仅命名的成员。你要么需要像&Employee::GetDes那样取他们的地址,要么像Employee::GetDes()那样给他们打电话。您还可能希望确保实际返回结果,但仅调用成员即可,尽管不太可能产生所需的结果。