简单的C++继承示例,有什么问题?

5
我正在尝试编译这个代码,但是无法确定问题所在。我使用MacOSX Snow Leopard和Xcode g++版本4.2.1。有人能告诉我问题出在哪里吗?我认为这应该可以编译。这不是我的作业,我是一名开发者......至少我认为我是,直到我被这个问题难住了。我收到以下错误消息:
error: no matching function for call to ‘Child::func(std::string&)’
note: candidates are: virtual void Child::func()

这是代码:

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

刚刚一个小时前,有人遇到了这个问题:http://stackoverflow.com/questions/6034869/c-inheritence - Nawaz
1个回答

11

Child::func() 的存在会隐藏 所有Parent::func 重载函数,包括 Parent::func(string&)。你需要加上一个 "using" 指令:

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

编辑: 或者,您可以自行指定正确的范围:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接