7、C++基礎(chǔ):內(nèi)存動(dòng)態(tài)分配與釋放、引用

#include <iostream>
using namespace std;

// 內(nèi)存分配和釋放
void Memory(){
  int *p = new int; // 動(dòng)態(tài)申請內(nèi)存
  cin >> *p;
  cout << *p << endl;
  delete p;

  int *q = new int(5); // 動(dòng)態(tài)申請內(nèi)存并賦值
  cout << *q << endl;
  delete q;

    int *m = new int[5];
    for (int i = 0; i < 5; ++i) {
    *(m+i) = i+1;
  }
    for (int i = 0; i < 5; ++i) {
    cout << *(m+i) << '\t';
    cout << endl;
  }
    delete[] m; // 刪除內(nèi)存,delete[]針對數(shù)組
}

// 引用
void Reference(){
    int a;
    int &b = a; // 引用:a取了一個(gè)別名叫b,所有對b的操作都是直接作用于a,a和b指向同一個(gè)地址
    b = 5;
    cout << a << endl;
    cout << &a << endl;
    cout << &b << endl;

    b++;
    cout << a <<':' << b << endl;
    cout << &a << endl;
    cout << &b << endl;
}

// 函數(shù)參數(shù)引用
int fun(int &n){
  return (n++)-1;
}
void ReferenceParam(){
  int a = 5;
  cout << a << endl;
  cout << fun(a) << endl;
  cout << a << endl;
}

// 外部變量 extern
// extern是C/C++語言中表明函數(shù)和全局變量作用范圍(可見性)的關(guān)鍵字,該關(guān)鍵字告訴編譯器,其聲明的函數(shù)和變量可以在本模塊或其它模塊中使用
// extern int a;僅僅是一個(gè)變量的聲明,其并不是在定義變量a,并未為a分配內(nèi)存空間。變量a在所有模塊中作為一種全局變量只能被定義一次,否則會(huì)出現(xiàn)連接錯(cuò)誤
// 與extern對應(yīng)的關(guān)鍵字是static,被它修飾的全局變量和函數(shù)只能在本模塊中使用。
void ExternParam(){
  extern int a;
  cout << a << endl;
  a++;
  cout << a << endl;
}
int a = 7;


extern const int b = 2;
extern const int c;
void ExternConstParam(){
  cout << b << endl;
  cout << c << endl;
}
const int c = 3;


int main(void){

  cout << "內(nèi)存分配和釋放" << endl;
  Memory();

  cout << "\n引用" << endl;
  Reference();

  cout << "\n函數(shù)參數(shù)引用" << endl;
  ReferenceParam();

  cout << "\n外部變量" << endl;
  ExternParam();

  cout << "\n外部常量" << endl;
  ExternConstParam();

  return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容