繁体   English   中英

将派生对象作为基类参考参数传递

[英]passing derived object as base class reference parameter

此示例显示了派生类对象被传递给以引用基类为参数的函数。 派生类中的成员函数g(int)在基类中隐藏g(float) 我了解这一点,而我的问题与此无关。

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;
}

输出为:

Base::g(float)
Derived::g(int)

我的问题是输出“ Base :: g(float)”。 由于sampleTwo()中由'b'引用的对象是派生对象,因此动态绑定不应该调用派生类的g()方法(将float转换为int)吗?

g(int)g(float)是两种完全不同的方法。 Derived::g(int)不会覆盖Base::g(float) 这些方法无关。

由于“ Derived ”不会覆盖g(float) ,因此您对bg(3.14f)期望是没有根据的。 如预期的那样, bg(3.14f)应该调用Base::g(float)

如果您在Derived重写g(float) ,则bg(3.14f)确实会调用Derived::g(float)

动态调度将调用最终的替代程序。 由于Derived::g隐藏,而不是覆盖Base::g ,最后超控器Base::gDerived仍然Base::g

g(float)g(int)是不同的函数成员。 如果要让Derived工作,则必须在两个类中都使用g(float)

可以重载g()来检查函数重载: https : //en.wikipedia.org/wiki/Function_overloading

示例(同一类中的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM