#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的值也會改變
}