这段代码是如何工作的?

时间:2016-01-18 14:46:38

标签: c++ virtual-functions

#include<iostream>
using namespace std;

class base {
public:
    virtual void func()
    {
        cout << "Using base version of func()\n";
    }
};


class derived1 : public base {

    void func()
    {
        cout << "Using derived1's version of func()\n";
    }
};

// Derived2 inherits derived1.
class derived2 : public derived1 {

    void func()
    {
        cout << "Using derived2's version of func()\n";
    }
};


int main()
{
    base *p, ob;
    derived1 d_ob1;
    derived2 d_ob2;

    p = &ob;
    //ob.func();
    p->func(); // use base's func()


    p = &d_ob1;
    p->func(); // use derived1's func()

    p = &d_ob2;
    p->func(); // use derived2's func()

    return 0;
}

此代码的输出为:

使用func()的基本版本

使用derived1的func()版本

使用derived2的func()版本

指针如何访问派生类的私有方法?

0 个答案:

没有答案