Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

inheritance - C++ override/overload problem

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

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*)

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...