2013级C++第12周(春)项目——成员的访问属性、多重继承【 第2部分 实践项目】

来源:互联网 发布:c语言如何实现多线程 编辑:程序博客网 时间:2024/06/06 01:35
1.公有继承
/** 程序的版权和版本声明部分* Copyright (c)2014, 在校学生* All rightsreserved.* 文件名称: 1.cpp* 作    者:  刘旺* 完成日期:2014年5月12日* 版本号: v1.0* 输入描述:无* 问题描述: 理解基类中成员的访问限定符和派生类的继承方式*/#include <iostream>using namespace std ;class Animal{//动物类 public:       Animal(){}       void eat(){           cout << "eat" << endl ;       } protected :       void play(){           cout << "play" << endl ;       } private:      void drink() {         cout << "drink" << endl ;      }};class Giraffe: public Animal{//长颈鹿public :      Giraffe(){}      void StrechNeck(){          cout << "SrechNeck" << endl ;      }private:    void take()    {        eat() ;//正确:公有继承下,基类的公有成员对派生类可见        play() ;//正确:play成员函数为保护成员函数通过公有继承变为私有成员函数        drink() ;//错误:drink通过公有继承变为不可访问    }};int main(){    Giraffe gir ;    gir.eat() ;//正确:eat为公有成员函数    gir.play() ;//错误:play通过公有继承变为私有成员函数所以外界不可访问    gir.drink() ;//错误:drink为私有成员    gir.take() ;//错误:take为私有成员函数外界不能访问    gir.StrechNech() ;//正确:StrechNech为公有成员函数所以对类外可见    Animal ani ;    ani.eat() ;//正确:eat在animal类中属于公有成员函数所以对外界可见    ani.drink() ;//错误:drink为私有成员函数所以外界不可访问    ani.play() ;//错误:play成员函数为保护成员函数所以类外不可访问    ani.take() ;//错误:因为Animal类中并没有take成员函数    ani.StrechNech() ;//错误:因为Animal类中并没有StrechNech成员函数    return 0 ;}
2.私有继承
#include <iostream>using namespace std ;class Aniaml{   public:        Animal() {}        void eat(){           cout << "eat" << endl ;        }   protected:       void play(){           cout << "play" << endl ;       }   private:       void drink(){           cout << "drink" << endl ;       }};class Giraffe:private Animal{   public:       Giraffe() {}       void strechNech() {           cout << "StrechNech" << endl ;       }       void take(){           eat() ;//正确:eat为公有成员函数通过私有继承成为成为私有成员函数           play() ;//正确:play为保护成员函数通过私有继承成为私有成员函数           drink() ;//错误:drink为私有成员函数通过私有继承成为不可访问       }};int main() {   Giraffe gir ;   gir.eat() ;//错误:eat为私有成员函数对类外不可见   gir.play() ;//错误:play为私有成员函数对类外不可见   gir.drink() ;//错误:drink不可见   return 0 ;}

3.保护继承

#include <iostream>using namespace std ;class Animal{public:    Animal(){}    void eat(){       cout << "eat" << endl ;    }protected:    void play(){        cout << "play" << endl ;    }private:    void drink(){        cout << "drink" << endl ;    }};class Giraffe:protected Animal{public:     Giraffe(){}     void strechNeck(){         cout << "StrechNeck" << endl ;     }     void take(){         eat() ;//正确:eat为公有成员函数通过保护继承成为保护成员函数         play() ;//正确:play为保护成员函数通过保护继承成为保护成员         drink() ;//错误:drink为私有成员数通过保护继承不可见     }};int main(){    Giraffe gir ;    gir.eat() ;//错误保护成员函数不可见    gir.play() ;//错误:保护成员函数不可见    gir.drink() ;//错误:不可见    return 0 ;}

这个必须要好好复习一下啦有遗忘啦

0 0