C ++覆盖/过载问题

时间:2009-09-27 22:24:22

标签: c++ inheritance g++ override overloading

我在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和编译错误:

$ 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 ++ bug还是来自g ++的随机消息,以防止我看不到的特殊情况?

1 个答案:

答案 0 :(得分:11)

问题是在派生类中,您将受保护的方法隐藏在基类中。您可以执行以下操作:要么完全限定派生对象中的受保护方法,要么使用using指令将该方法带入范围:

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
  }
};