Simple C++ Inheritance Example, What's wrong?

2019-04-29 18:04发布

问题:

Possible Duplicate:
Function with same name but different signature in derived class

I'm trying to compile this and I can't figure out what is wrong with the code. I'm using MacOSX Snow Leopard with Xcode g++ version 4.2.1. Can someone tell me what the issue is? I think this should compile. And this is not my homework I'm a developer...at least I thought I was until I got stumped by this. I get the following error message:

error: no matching function for call to ‘Child::func(std::string&)’
note: candidates are: virtual void Child::func()

Here is the code:

#include <string>

using namespace std;

class Parent
{
public:
  Parent(){}
  virtual ~Parent(){}
  void set(string s){this->str = s;}
  virtual void func(){cout << "Parent::func(" << this->str << ")" << endl;}
  virtual void func(string& s){this->str = s; this->func();}
protected:
  string str;
};

class Child : public Parent
{
public:
  Child():Parent(){}
  virtual ~Child(){}
  virtual void func(){cout << "Child::func(" << this->str << ")" << endl;}
};

class GrandChild : public Child
{
public:
  GrandChild():Child(){}
  virtual ~GrandChild(){}
  virtual void func(){cout << "GrandChild::func(" << this->str << ")" << endl;}
};

int main(int argc, char* argv[])
{
  string a = "a";
  string b = "b";
  Child o;
  o.set(a);
  o.func();
  o.func(b);
  return 0;
}

回答1:

The presence of Child::func() hides all overloads of Parent::func, including Parent::func(string&). You need a "using" directive:

class Child : public Parent
{
public:
  using Parent::func;
  Child():Parent(){}
  virtual ~Child(){}
  virtual void func(){cout << "Child::func(" << this->str << ")" << endl;}
};

EDIT: Or, you may specify the correct scope yourself:

int main(int argc, char* argv[])
{
  string a = "a";
  string b = "b";
  Child o;
  o.set(a);
  o.func();
  o.Parent::func(b);
  return 0;
}


标签: c++ oop