c++ 继承关系中的函数调用

c++ 考试注意

<!-- lang: cpp -->


    #include<iostream>
    using namespace std;

    class base
    {
        private: 

        public:
            virtual void f(){cout << "base::f()" << endl;}
            void f2(){f();cout << "base::f2()" << endl;}
        //  base(){cout << "base::" <<endl;};
        //  virtual ~base(){cout << "base::\n" ;cin.get();}
    };

    class deprived : public base
    {
        private:
            //int data;
        public:
            void f(){cout<<"deprived::f()"<<endl;}
            //void f3(){cout << "deprived::f2()"<<endl;}
            void f3(){cout << "deprived::f3()" <<endl;}
            //deprived():data(1){}
            //virtual ~deprived(){cout << "deprived::\n" ;}
    };

    class deprived2 : public deprived
    {
        public:
            void f2(){cout << "deprived2::f2()" << endl;}
            void f(){cout << "deprived2::f()" << endl;};
    };

    int main() 
    {
        deprived *d2 = new deprived2;
        d2->f2();
        cin.get();

        return 0;

    }

运行结果如下图:
(主要是deprived2 没有f2(); 不过如果base类的f2()改成虚函数,那么结果就是直接调用deprived2中的f2(),也就是说:结果结果会变为deprived2::f2();)
c++ 继承关系中的函数调用_第1张图片

你可能感兴趣的:(c++ 继承关系中的函数调用)