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
发生编译错误


[img]http://dl.iteye.com/upload/attachment/0077/0975/5b49820a-3a78-3561-9f33-4c5fbbbf0563.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值