[英]passing derived object as base class reference parameter
This examples shows a derived class object being passed to a function which takes reference to base class as the parameter. 此示例显示了派生类对象被传递给以引用基类为参数的函数。 Member function g(int)
in the derived class hides the g(float)
in the base class. 派生类中的成员函数g(int)
在基类中隐藏g(float)
。 I understand that and my question is not related to it. 我了解这一点,而我的问题与此无关。
class Base {
public:
virtual void g(float x) throw()
{
cout << "Base::g(float)\n";
}
};
class Derived : public Base {
public:
virtual void g(int x) throw() // Bad: Hides Base::g(float)
{
cout << "Derived::g(int)\n";
}
};
void sampleTwo(Base& b, Derived& d)
{
b.g(3.14f);
d.g(3.14f); // Bad: Converts 3.14 to 3 and calls Derived::g(int)
}
int main()
{
Derived d;
sampleTwo(d, d);
return 0;
}
Output is: 输出为:
Base::g(float)
Derived::g(int)
My question is with the output "Base::g(float)". 我的问题是输出“ Base :: g(float)”。 Since the object referenced by 'b' in sampleTwo() is derived object, shouldn't the dynamic binding call the g() method of the derived class (converting float to int) ? 由于sampleTwo()中由'b'引用的对象是派生对象,因此动态绑定不应该调用派生类的g()方法(将float转换为int)吗?
g(int)
and g(float)
are two completely different methods. g(int)
和g(float)
是两种完全不同的方法。 Derived::g(int)
does not override Base::g(float)
. Derived::g(int)
不会覆盖Base::g(float)
。 These methods are unrelated. 这些方法无关。
Since Derived
does not override g(float)
, your expectations about bg(3.14f)
are unfounded. 由于“ Derived
”不会覆盖g(float)
,因此您对bg(3.14f)
期望是没有根据的。 As expected, bg(3.14f)
should call Base::g(float)
. 如预期的那样, bg(3.14f)
应该调用Base::g(float)
。
If you override g(float)
in Derived
, then bg(3.14f)
will indeed call Derived::g(float)
. 如果您在Derived
重写g(float)
,则bg(3.14f)
确实会调用Derived::g(float)
。
Dynamic dispatch invokes the final overrider. 动态调度将调用最终的替代程序。 Since Derived::g
hides rather than overrides Base::g
, the final overrider of Base::g
in Derived
is still Base::g
. 由于Derived::g
隐藏,而不是覆盖Base::g
,最后超控器Base::g
在Derived
仍然Base::g
。
g(float)
and g(int)
are different function members. g(float)
和g(int)
是不同的函数成员。 If you want Derived
to work, you have to use g(float)
in both classes. 如果要让Derived
工作,则必须在两个类中都使用g(float)
。
g()
can be overloaded check out function overloading: https://en.wikipedia.org/wiki/Function_overloading 可以重载g()
来检查函数重载: https : //en.wikipedia.org/wiki/Function_overloading
Example ( g(float)
and g(int)
in the same class and separate functions): 示例(同一类中的g(float)
和g(int)
和不同的函数):
class Derived : public Base {
public:
void g(float x) throw();
void g(int x) throw();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.