天天看點

C++ Printer Plus學習筆記 第八章 内聯函數 引用

示例:

#include <iostream>

// 關鍵字 inline 代碼塊必須簡短
inline double square(double x) {return x * x; }

int main()
{
  using namespace std;
  double a, b;
  double c = 13.0;

  a = square(5.0);
  b = square(4.5 + 7.5);
  cout << "a = " << a << ", b = " << b << "\n";
  cout << "c = " << c;
  cout << ", c squared = " << square(c++) << "\n";
  cout << "Now c = " << c << "\n";
  return 0;
}
           
C++ Printer Plus學習筆記 第八章 内聯函數 引用

引用

#include <iostream>
int main()
{
  using namespace std;
  int rats = 101;
  int& rodents = rats;
  cout << "rats = " << rats;
  cout << ", rodents = " << rodents << endl;
  rodents++;
  cout << "rats = " << rats;
  cout << ", rodents = " << rodents << endl;

  cout << "rats address = " << &rats;
  cout << ", rodents address = " << &rodents << endl;
  return 0;
}
           

其實引用是指針的僞裝:

int rats = 101;

int& rodents = rats;

int* const prats = &rats  要留意 const是在裡面 也就是說 該指針變量不能指向其他位址

parts = rodents

引用變量無法通過指派語句改變其記憶體位址 且指針不允許指派給引用變量。

C++标準中  對于函數形參使用const 修飾符的引用變量  允許傳遞類型不正确或不是左值的資料。因為C++會建立臨時變量

如果沒有const修飾符的話 則不允許這麼幹(有一些舊的編譯器隻是報錯 但是依然通過編譯)

C++ Printer Plus學習筆記 第八章 内聯函數 引用

four為結構類型的變量 

accumulate傳回dup(與four是同一種結構資料類型)的引用

是以如下的指派語句的順序是:

accumulate(dup, five) = four;

==

dup = accumulate(dup, five)

dup = four

繼續閱讀