c++中什麼是引用,什麼是指標。
引用就是引用地址,給變數取個小名,這個都可以改變變數的數值。
程式碼:
#include <iostream>
using namespace std;
int main ()
{
// 宣告簡單的變數
int i;
double d;
// 宣告引用變數
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
結果::
Value of i : 5 Value of i reference : 5 Value of d : 11.7 Value of d reference : 11.7
指標也是一種儲存,只不過存的是地址,用*取取出地址所對應的數值:
上程式碼:
#include <iostream>
using namespace std;
int main ()
{
int var = 20; // 實際變數的宣告
int *ip; // 指標變數的宣告
ip = &var; // 在指標變數中儲存 var 的地址
cout << "Value of var variable: ";
cout << var << endl;
// 輸出在指標變數中儲存的地址
cout << "Address stored in ip variable: ";
cout << ip << endl;
// 訪問指標中地址的值
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
程式碼結果:
Value of var variable: 20 Address stored in ip variable: 0x7fff5bfda1d8 Value of *ip variable: 20