简单C ++继承示例,有什么问题? [英] Simple C++ Inheritance Example, What's wrong?
问题描述
可能重复:
在派生类中具有相同名称但具有不同签名的函数
我试图编译这个,我不知道什么是错误的代码。我使用MacOSX雪豹与Xcode g ++版本4.2.1。有人能告诉我这是什么问题吗?我认为这应该编译。这不是我的家庭作业我是一个开发商...至少我以为我是,直到我被这个骗了。我得到以下错误消息:
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()
代码:
#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;
}
推荐答案
$ c> Child :: func()隐藏 Parent :: func
的所有重载,包括 Parent :: func(string&)
。您需要一个using指令:
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;}
};
编辑:
或者,您可以自行指定正确的范围:
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 ++继承示例,有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!