VC++ 基礎(一)

來源:互聯網
上載者:User

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.