c++

作者: 小雨启明 | 来源:发表于2018-09-18 00:07 被阅读0次

    转载:https://blog.csdn.net/gogogo_sky/article/details/72860426

    20170605211105168.png
    简单示例:

    重新定义

    #include<iostream>
    using namespace std;
    
    class a {
    public:
        void fun() {
            cout << "a";
        }
    };
    
    class b:public a {
    public:
        void fun(int s) {
            cout << "b";
        }
    };
    
    class c :public a {
    
    };
    
    int main() {
        b* b1 = new b();
        b1->fun(2); //子类中重新实现
        c* c1 = new c();
        c1->fun();//子类中没有重新实现
    }
    

    重写

    #include<iostream>
    using namespace std;
    
    class a {
    public:
        virtual void fun() {
            cout << "a"<<endl;
        }
        void fun2() {
            cout << "a no virtual" << endl;
        }
    };
    
    class b:public a {
    public:
        void fun() {
            cout << "b"<<endl;
        }
    };
    
    class c :public a {
        void fun(int cval) {
            cout << "c" << endl;
        }
        void fun2() {
            cout << "c no virtual" << endl;
        }
    };
    
    int main() {
        a* b1 = new b();
        b1->fun();//b中重写
        a* c1 = new c();
        c1->fun();//c中无重写
        c1->fun2();
    }
    

    相关文章

      网友评论

          本文标题:c++

          本文链接:https://www.haomeiwen.com/subject/fmnzgftx.html