`

C++继承

    博客分类:
  • C++
c++ 
阅读更多
// Console03.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class Animal
{
   public:
   void eat()
   {
          cout<<"animal eat"<<endl;
   }
   void sleep()
   {
          cout<<"animal sleep"<<endl;
   }
   void breathe()
   {
          cout<<"animal breathe"<<endl;
   }
  
};

class Fish:public Animal
{

};

void main()
{
   Animal an;
   an.eat();
   Fish fh;
   fh.sleep();

   int i;
   cin>>i;
}

和C#一样它是用冒号来继承
Fish从Animal派生而来
所以fh也可以调用sleep方法

运行结果为:
animal eat
animal sleep

----------------------------------------------------------------------------------

// Console03.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class Animal
{
   public:
   void eat()
   {
          cout<<"animal eat"<<endl;
   }
   protected:
   void sleep()
   {
          cout<<"animal sleep"<<endl;
   }
   void breathe()
   {
          cout<<"animal breathe"<<endl;
   }
  
};

class Fish:public Animal
{
  public:
  void test()
  {
  this->sleep();   //在子类里可以调用父类的protected方法
  }
};

void main()
{
   Animal an;
   an.eat();
   Fish fh;
  // fh.sleep();    这里的调用不成功,编译错误
   fh.test();
   int i;
   cin>>i;
}

现在把sleep和breathe方法设置为protected的了
这样在子类里能访问它们 但是在main函数里就没有权限调用了

--------------------------------------------------------------------------------

// Console03.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class Animal
{
   public:
   void eat()
   {
          cout<<"animal eat"<<endl;
   }
   protected:
   void sleep()
   {
          cout<<"animal sleep"<<endl;
   }
   private:
   void breathe()
   {
          cout<<"animal breathe"<<endl;
   }
  
};

class Fish:public Animal
{
  public:
  void test()
  {
  this->sleep();
  this->breathe();
  }
};

void main()
{
   Animal an;
   an.eat();
   Fish fh;
  // fh.sleep();
   fh.test();
   int i;
   cin>>i;
}

现在把breathe设置为private的了
所以在子类中也访问不了breathe
发生编译错误





分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics