简单的C++继承示例,出了什么问题?
Simple C++ Inheritance Example, What's wrong?
可能的重复项:
派生类中名称相同但签名不同的函数
我正在尝试编译它,但我无法弄清楚代码出了什么问题。 我正在使用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()
的存在隐藏了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;
}
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了