2011-05-17 50 views
5

可能重复:
Function with same name but different signature in derived class简单的C++继承示例,有什么问题?

我试图编译此,我无法弄清楚什么是错的代码。我使用Xcode g ++ 4.2.1版的MacOSX Snow Leopard。有人能告诉我这是什么问题吗?我认为这应该编译。这不是我的作业,我是一名开发人员...至少我认为我一直是被这个难住了。我收到以下错误信息:

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

短短一小时回别人有这个问题:HTTP://计算器。 com/questions/6034869/c-inheritence – Nawaz 2011-05-17 19:14:25

回答

11

Child::func()存在隐藏所有重载Parent::func,包括Parent::func(string&)。你需要一个“使用”指令:

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

谢谢!正是我需要的! – bantl23 2011-05-17 19:20:24