C++學習筆記十四之函數參數傳遞

函數參數傳遞

傳參方式

  • 值傳遞
  • 址傳遞
    • 若是想經過參數改變某一個變量的值,實參爲該變量的地址。稱爲址傳遞
  • 引用傳遞
    • 引用傳遞:形參是引用類型,實參必須是變量名

數組做爲函數的形參

  • 弱化爲指針類型 大小爲4個字節
  • 數組做爲函數形參時,必須添加一個參數做爲數組大小

練習代碼

//值傳遞
void change(int a, int b) {
	int t = a;
	a = b;
	b = t;
	cout << "a=" << a << endl;//20
	cout << "b=" <<b << endl;//10
}
//址傳遞
void change(int *pa, int *pb) {

	int t = *pa;
	*pa = *pb;
	*pb = t;
	cout << "a=" << *pa << endl;//20
	cout << "b=" << *pb << endl;//10
}
//引用傳遞
void change1(int& a, int& b) {
	int t = a;
	a = b;
	b = t;
	cout << "a=" << a << endl;//10
	cout << "b=" << b << endl;//20
}
void GetMemory(int **p) {
	*p = new int;//假設申請的內存首地址爲0x00FF00FF
}
void PrintArray(int n[100],int size) {
	cout <<sizeof(n) << endl;//4

	for (int i = 0; i < size;i++)
	{
		cout << n[i] << endl;
	}
}
int main() {
	int n[6] = {};
	PrintArray(n,6);

	int *p = nullptr;
	GetMemory(&p);
	cout << p << endl;
	delete p;
	p = nullptr;

	int a = 10, b = 20;
	change(a, b);
	cout << "a=" << a << endl;//10
	cout << "b=" << b << endl;//20

	change(&a, &b);
	cout << "a=" << a << endl;//20
	cout << "b=" << b << endl;//10

	change1(a, b);
	cout << "a=" << a << endl;//10
	cout << "b=" << b << endl;//20
	return 0;
}
複製代碼
相關文章
相關標籤/搜索