[英]Calling the right overloaded parent method
I have a question regarding method overloading and inheritance. 我有一个关于方法重载和继承的问题。 I have the following program:
我有以下程序:
class Face {};
class Point {};
typedef double Real;
class Func
{
private:
const char *m_name, *m_desc;
public:
Func(const char *name,
const char *desc) : m_name(name), m_desc(desc) {}
virtual Real value(Face &f) = 0;
Real value(Point &p) {return 0.;}
virtual ~Func() {}
};
class QuadFunc : public Func
{
public:
QuadFunc() : Func("quad", "Quadratic") {}
Real value(Face &f) override {return 0.;}
};
int main(int argc, char **argv)
{
QuadFunc func;
Face f;
Point p;
func.value(f);
// why doesn't this work?
func.value(p);
return 0;
}
Sadly g++ tells me that there is "no matching function for call to 'QuadFunc::value(Point&)'". 可悲的是,g ++告诉我“没有匹配函数来调用'QuadFunc :: value(Point&)'”。 As far as I am concerned if I call QuadFunc::value(Point&) the call should be redirected to the parent class Func.
就我而言,如果我调用QuadFunc :: value(Point&),则应将调用重定向到父类Func。 This does work if I rename value(Point &p) to p_value(Point &p) and call that method instead.
如果我将值(Point&p)重命名为p_value(Point&p)并调用该方法,则此方法有效。 Can I somehow get the overloaded method to work as I expect?
我能以某种方式使重载方法按我的预期工作吗?
Your override in QuadFunc
hides the overloaded function in Func
. 在
QuadFunc
覆盖将在Func
隐藏重载函数。
You can bypass this hiding, by using a Func
reference (or pointer) to a QuadFunc
object: 您可以通过使用对
QuadFunc
对象的Func
引用(或指针)来绕过此隐藏:
QuadFunc qf;
Func &func = qf;
Face f;
Point p;
func.value(f);
func.value(p); // Works
A better solution is to "import" the value
symbol into the QuadFunc
class from the Func
class. 更好的解决方案是将
value
符号从Func
类“导入”到QuadFunc
类中。 You do that with the using
keyword: 您可以
using
关键字:
class QuadFunc : public Func
{
public:
using Func::value;
// ...
};
Then you don't have to use the reference workaround. 然后,您不必使用参考解决方法。
You need to use the using
directive if you want to overload a member function from a base class (also you might need the already mentioned virtual
), so the code will become: 如果要从基类中重载成员函数,则需要使用
using
指令(也可能需要已提到的virtual
),因此代码将变为:
class QuadFunc : public Func
{
public:
QuadFunc() : Func("quad", "Quadratic") {}
using Func::value; //this is what you need
Real value(Face &f) override {return 0.;}
};
The virtual function is hiding the function value(Point&), if you are explicit to the compiler as in: 如果您对编译器是显式的,则虚拟函数将隐藏函数值(Point&),如下所示:
func.Func::value(p);
it does work! 它确实有效! Test it here .
在这里测试。
In alternative you can just add 另外,你可以添加
using Func::value;
into the QuadFunc declaration, as suggested by another answer. 如另一个答案所示,进入QuadFunc声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.