Exceptional C++

【Exceptional C++(10)】改写虚函数

2018-01-29  本文已影响6人  downdemo

问题

#include <iostream>
#include <complex>
using namespace std;
class Base
{
public:
    virtual void f(int);
    virtual void f(double);
    virtual void g(int i = 10);
};
void Base::f(int)
{
    cout << "Base::f(int)" << endl;
}
void Base::f(double)
{
    cout << "Base::f(double)" << endl;
}
void Base::g(int i)
{
    cout << i << endl;
}
class Derived : public Base
{
public:
    void f(complex<double>);
    void g(int i = 20);
};
void Derived : f(complex<double>)
{
    cout << "Derived::f(complex)" << endl;
}
void Derived::g(int i)
{
    cout << "Derived::g()" << i << endl;
}
int main()
{
    Base b;
    Derived d;
    Base* pb = new Derived;
    b.f(1.0);
    d.f(1.0);
    pb->f(1.0);
    b.g();
    d.g();
    pb->g();
    delete pb;
}

解答

int main()
{
    Base b;
    Derived d;
    Base* pb = new Derived;
    b.f(1.0);
    // 调用Base::f(double)
    d.f(1.0);
    // 这次调用Derived::f(complex<double>),因为Base::f被隐藏了
    // complex提供了隐式转换,实际相当于Derived::f(complex<double>(1.0))
    pb->f(1.0);
    // 调用Base::f(double),因为派生类没有Derived::f(double)
    b.g();
    // 调用Base::g(10)
    d.g();
    // 调用Derived::g(20)
    pb->g();
    // 调用Derived::g(10),因为默认参数由静态类型(pb是Base)决定
    delete pb;
}
上一篇下一篇

猜你喜欢

热点阅读