C ++覆盖/重载问题 [英] C++ override/overload problem

查看:84
本文介绍了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 ?

推荐答案

问题是,在派生类中,您将在基类中隐藏受保护的方法。你可以做一些事情,要么你完全限定了派生对象中的protected方法,要么使用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 ++覆盖/重载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆