c++将引用作为函数的参数---6
生活随笔
收集整理的這篇文章主要介紹了
c++将引用作为函数的参数---6
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
原創(chuàng)博客:轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://www.cnblogs.com/zxouxuewei/
?
引用經(jīng)常被用作函數(shù)參數(shù),使得函數(shù)中的變量名成為調(diào)用程序中的變量別名。這種傳遞參數(shù) 的方法稱為按引用傳遞。按引用傳遞允許被調(diào)用的函數(shù)能夠訪問調(diào)用函數(shù)中的變量。C++新增這項(xiàng)特性是對(duì)C語(yǔ)言的超越,C語(yǔ)言只能按值傳遞。按值傳遞導(dǎo)致被 調(diào)用函數(shù)使用調(diào)用程序的值得拷貝。當(dāng)然,C語(yǔ)言也允許避開按值傳遞的限制,采用按指針傳遞的方式。
代碼:
#include <stdio.h> #include <iostream> using namespace std; void TestAddress1(int p, int& a, int b) { cout << "TestAddress1" << endl; cout << "p address:" << &p << "; p value:" << p << endl; cout << "a address:" << &a << "; a value:" << a << endl; cout << "b address:" << &b << "; b value:" << b << endl; int* c = &b; c -= 2; cout << "c address:" << c << "; c value:" << *c << endl; } void TestAddress2(int* a, int b) { cout << "TestAddress2" << endl; cout << "a address:" << &a << "; a value:" << *a << endl; cout << "b address:" << &b << "; b value:" << b << endl; } int main() { int* a = new int[5]; memset(a, 0, sizeof(int)* 5); a[0] = 123; int b = 2; int c = 3; cout << "out a address:" << &a << endl; cout << "out b address:" << &b << endl; cout << "out c address:" << &c << endl; cout << "-----------------" << endl; TestAddress1(b, b, c); cout << "-----------------" << endl; TestAddress2(a, b); }?
總結(jié)
以上是生活随笔為你收集整理的c++将引用作为函数的参数---6的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java集合归纳
- 下一篇: (iOS开发总结)MVC模式