C++ override/overload problem(C++ 覆盖/重载问题)
问题描述
我在 C++ 中遇到了一个问题:
I'm facing a problem in C++ :
#include <iostream>
class A
{
protected:
void some_func(const unsigned int& param1)
{
std::cout << "A::some_func(" << param1 << ")" << std::endl;
}
public:
virtual ~A() {}
virtual void some_func(const unsigned int& param1, const char*)
{
some_func(param1);
}
};
class B : public A
{
public:
virtual ~B() {}
virtual void some_func(const unsigned int& param1, const char*)
{
some_func(param1);
}
};
int main(int, char**)
{
A* t = new B();
t->some_func(21, "some char*");
return 0;
}
我使用的是 g++ 4.0.1 和编译错误:
I'm using g++ 4.0.1 and the compilation error :
$ g++ -W -Wall -Werror test.cc
test.cc: In member function ‘virtual void B::some_func(const unsigned int&, const char*)’:
test.cc:24: error: no matching function for call to ‘B::some_func(const unsigned int&)’
test.cc:22: note: candidates are: virtual void B::some_func(const unsigned int&, const char*)
为什么我必须指定 B 类中 some_func(param1) 的调用是 A::some_func(param1) ?是 g++ 错误还是来自 g++ 的随机消息,以防止我看不到的特殊情况?
Why do I must specify that the call of some_func(param1) in class B is A::some_func(param1) ? Is it a g++ bug or a random message from g++ to prevent special cases I don't see ?
推荐答案
问题是在派生类中,您将受保护的方法隐藏在基类中.您可以做几件事,要么完全限定派生对象中的受保护方法,要么使用 using 指令将该方法带入作用域:
The problem is that in the derived class you are hiding the protected method in the base class. You can do a couple of things, either you fully qualify the protected method in the derived object or else you bring that method into scope with a using directive:
class B : public A
{
protected:
using A::some_func; // bring A::some_func overloads into B
public:
virtual ~B() {}
virtual void some_func(const unsigned int& param1, const char*)
{
A::some_func(param1); // or fully qualify the call
}
};
这篇关于C++ 覆盖/重载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 覆盖/重载问题
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
