gpt4 book ai didi

c++ - 调用基类的 protected 函数时出错

转载 作者:行者123 更新时间:2023-11-28 05:54:56 25 4
gpt4 key购买 nike

我是 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<< .我没有打印任何类(class)。我这里只是调用派生类的函数。

最佳答案

如前所述,派生类 Work::GetNamevoid所以它没有返回任何值。您可以将其更改为:

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

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

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


[编辑] 更改了“重新声明”代码以遵循当前的 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++ - 调用基类的 protected 函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com