VC++ 基础(一)

 

#include<iostream.h>

class Animal{
public://任何地方都可以访问
 //构造方法:1、与类名相同。2、没有返回值。3、可以带参数
 Animal(){
  //cout<<"Animal construct"<<endl;
 }
 Animal(int height,int weight){
  //cout<<"Animal construct"<<endl;
 }
 //析构方法:1、不允许有返回值。2、不允许带参数。用于内存的释放
 ~Animal(){
  //cout<<"Animal deconstruct"<<endl;
 }
 void eat(){
  cout<<"animal eat"<<endl;
 }
//protected://只在自己、子类中可以访问
 void sleep(){
  cout<<"animal sleep"<<endl;
 }
//private://只有 自己 可以访问 
 /*
  会采用迟绑定(late binding)的技术
  如果子类没有breathe函数就调用基类的,如果有就调用子类的
 */
 //virtual 虚函数
 virtual void breathe(){
  cout<<"animal breathe"<<endl;
 }
 /*
  virtual void breathe()=0;
  纯虚函数
  含有纯虚函数的类叫抽象类
  只要子类实现了纯虚函数时,才能实例化。否则不能实例化子类
 */
 void get();
};
void Animal::get(){
 cout<<"animal get"<<endl;
}
class Fish : public Animal{//继承
public:
 //向基类传参数。可以省去:Animal(175,120)就不传参数。本身的常量a必须要初始化
 Fish():Animal(175,120),a(1)
 {
  //cout<<"Fish construct"<<endl;
 }
 ~Fish(){
  //cout<<"Fish deconstruct"<<endl;
 }
 //方法的覆盖。覆盖基类中的方法。
  void breathe(){//与父类的 虚函数进行区别
  //Animal::breathe();//声明该方法是基类中的breathe方法。::作用域标识符
  cout<<"Fish bubble"<<endl;
 }
private:
 const int a;
};
void fn(Animal *pAn){
 pAn->breathe();
}
void main(){
 Fish fh;
 //fh.breathe();
 Animal *pAn;//声明一个指针
 pAn=&fh;//把鱼的地址赋给这个指针、隐式转换
 fn(pAn);//输出是Animal对象:animal breathe

 int a=6;
 int &b=a;
 /*
  b是a的一个引用,b是a的一个别名。
  b指向a的地址。
  b维系在特定的目标(a)上面
  引用(&b)在定义的时候必须初始化。
  引用一般用在传参。语义更清晰
   change(x,y);
   change(&a,&b){};
 */
 b=6;//a的值也会改变
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值