C++---變量引用和類型別名(typedef)

引用的本質是變量的別名

Type var;
Type & n =var;

實例1

int a;
int & b = a;

int * const ptr = &a;
引用b的作用與*ptr相同

注意:聲明引用時必須初始化,不能先聲明再定義

錯誤實例

int n;
int &m;
m=n;
  • 引用與函數

在自定義函數中,如果形參爲非引用變量,函數調用時,生成實參的副本,在自定義函數中進行運算,實參不變;

如果使用引用變量做爲形參,調用函數時,直接對實參進行運算;

實例2

#include<iostream>
int addition_1(const int a,const int b);
void addone(int x);//非引用參數, copy副本,對副本進行處理(此處爲加1),原數不變  
void addthree(int& z);//引用形參 
using namespace std;
int main()
{
	int a=1,b=2,c=3;
	cout<<"調用函數前:"<<a<<endl;            //結果爲1 
	addone(a);
	cout<<"調用函數後:"<<a<<endl;            //結果爲1 
	
	cout<<"調用函數前:"<<c<<endl;           //結果爲3 
	addthree(c);//對c本身進行處理 
	cout<<"調用函數後:"<<c<<endl;           //結果爲6
	
	//const形參與非const形參。const形參保證copy的副本也不能改變 

	const int m=9,n=8;
	cout<<addition_1(m,n)<<endl;
	cout<<addition_1(a,b)<<endl;

   //a,b爲非常量,也能代入const形參,但是const不能傳給非const形參 

	return 0;
 } 
 void addone(int x)
 {
 	x+=1;
  } 

void addthree(int& z)
{
	z+=3;
 } 
 int addition_1(const int a,const int b)
 {
 	//a=a+1;invalid,常量不能改變 
 	return (a+b);
  } 

類型別名

C++存在兩種簡歷類型別名方式:

1.使用預處理器

#define wage float

預處理器在編譯程序時用float代替所有的wage,wage變爲float的別名

2.typedef

typedef不會產生新的數據類型,知識爲已有的類型建立新的名稱。

typedef typeName aliasName;

#include <iostream>
using namespace std;
typedef int wage;
typedef wage salary;
int main()
{
    typedef int fish,bird;
    fish sum=10;
    bird sum1=11;
    wage day,week,month,year;
    return 0;
}
  1. typedef 類型 類型別名1,類型別名...;
  2. 類型別名可以在函數內,也可以在函數前;

雖然兩種方法均能建立類型別名,但是第一種方法存在弊端。define只是一種簡單的字符替換,在下列情況下,會失效。

聲明兩個int *類型的變量;

#define address int*
address ptr1,ptr2;

我們希望聲明兩個地址類型的變量,但經過預處理器置換後,結果如下:

int *ptr1,ptr2;

ptr1爲地址,ptr2爲int型變量。

typedef 則不會出現這種情況。故推薦使用typedef創建類型別名。

像創建變量一樣,只需在前面加上關鍵字typedef即可創建類型別名。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章