美文网首页
动态多态-实现基类和派生类同名函数问题

动态多态-实现基类和派生类同名函数问题

作者: 始于尘埃 | 来源:发表于2019-07-28 20:05 被阅读0次
    //动态多态-实现基类和派生类同名函数问题
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Student{
        public:
            Student(int,string,float);
            virtual void display();
        protected:
            int num;
            string name;
            float score;
    };
    Student::Student(int n,string nam,float s){
        num = n;name = nam;score = s;
    }
    void Student::display(){
        cout<<"num:"<<num<<"\nname:"<<name<<"\nscore:"<<score<<"\n\n";
    }
    class Graduate:public Student{
        public:
            Graduate(int,string,float,float);
            void display();
        private:
            float wage;
    };
    Graduate::Graduate(int n,string nam,float s,float w):Student(n,nam,s),wage(w){
    }
    void Graduate::display(){
        cout<<"num:"<<num<<"\nname:"<<name<<"\nscore"<<score<<"\nwage="<<wage<<endl;
    }
    
    int main(){
        Student stu1(1000,"rice",87.9);
        Graduate grad1(2001,"Rice",90.0,1200);
        Student *pt = &stu1;
        pt->display();
        pt = &grad1;
        pt->display();    //同一个pt指针,实现对象的多态性,当然,你也可以用两个不同得指针实现,但这就不是多态性了(记住多态的定义) 
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:动态多态-实现基类和派生类同名函数问题

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