无法使用基类的方法
Unable to use method of base class
可能重复:
重载函数隐藏在派生类中
似乎我不能直接在派生类中使用基类中的方法,如果它们在C++中的基类和派生类中都重载了。以下代码产生错误no matching function for call to ‘Derived::getTwo()’
。
class Base {
public:
int getTwo() {
return 2;
}
int getTwo(int, int) {
return 2;
}
};
class Derived : public Base {
public:
int getValue() {
// no matching function for call to ‘Derived::getTwo()’
return getTwo();
}
int getTwo(int) {
return 2;
}
};
如果我将return getTwo();
更改为return ((Base*) this)->getTwo()
,它是有效的,但对我来说这看起来很难看。我该如何解决这个问题?
附言:如果这很重要的话,我使用g++4.7和std=gnu++c11选项。
任一:
class Derived : public Base {
public:
using Base::getTwo; // Add this line
int getValue() {
// no matching function for call to ‘Derived::getTwo()’
return getTwo();
}
int getTwo(int) {
return 2;
}
}
或
return Base::getTwo();
这就是C++中名称查找的工作方式:
namespace N1
{
int getTwo();
int getTwo(int, int);
namespace N2
{
int getTwo(int);
namespace N3
{
call getTwo(something char*);
}
}
}
当前上下文为N3。该层上没有getTwo
。好的,去上层。N2包含CCD_ 5的一个定义。编译器将尝试使用此定义,并且不会搜索上层上下文。来自N2的getTwo
隐藏了所有上层上的getTwo
的所有定义。有时这会导致重载方法的混乱。
如果添加using Base::getTwo;
,实际上就是向内部上下文添加了一个定义代理。上部上下文temsellves的定义不可见。但是代理是可见的。
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 将子类方法声明为基类的友元
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 在派生类中使用基类的私有成员变量的最佳方法
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 从基类实例调用派生类方法而不进行强制转换
- 继承:调用基类的成员和方法
- 通过基类接受方法转发派生 UniquePtr 的右值会移动引用而不是复制
- 引用基类模板的成员变量的简单方法
- C++ 使用派生类方法更改基类数据成员
- C++初始化之前派生类调用基类的方法
- 将派生类方法与基类unique_ptr一起使用
- 为什么派生类的实例从基类调用方法?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 从基类调用重写的方法
- 为什么允许将派生类的方法static_cast为基类的方法?
- C++-从方法基类调用派生类中的重写方法