可能的重复:
派生类中具有相同名称但不同签名的函数 https://stackoverflow.com/questions/411103/function-with-same-name-but-different-signature-in-derived-class
我正在尝试编译此代码,但我无法弄清楚代码有什么问题。我正在使用 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;
}
的存在Child::func()
hides all的过载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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)