调用基类的受保护函数时出错
Error while calling protected function of base class
我是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::GetName
是void
,因此不会返回任何值。您可以将其更改为:
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()
那样给他们打电话。您还可能希望确保实际返回结果,但仅调用成员即可,尽管不太可能产生所需的结果。
相关文章:
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- PrintWindow函数在notepad.exe中出错
- 使用运算符调用 void 函数时出错<set>
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 在定义的函数中使用常量时出错
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 使用根/C++时出错:没有匹配的构造函数来初始化'TTree'
- Arduino IDE 中使用 strncmp 函数时出错
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- 编译包含指向模板函数的指针的初始值设定项列表时,gcc 出错,但 clang 不出错
- 使用一个参数的模板函数时出错(适用于 2)
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 使用类的构造函数时出错
- 在 c++ 的构造函数中分配对象向量时出错
- 为什么在函数参数前面添加 const 会出错?
- 调用析构函数时出错