c++ 中在形参与实参之间的值传递

主要是对比直接传递与引用类型、指针类型之间的区别。

通过下面一段程序可以很清晰的看出三者在传递值还是传递拷贝的区别。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class MyClass
 5 {
 6 public:
 7     int a;
 8     void method();
 9 };
10 void MyClass::method()
11 {
12     cout<<"the last value of class:a after fun:"<<a<<'\n';
13 }
14 
15     void fun1(MyClass);
16     void fun2(MyClass*);
17     void fun3(MyClass&);
18 int main()
19 {
20     MyClass myclass;
21     myclass.a=10;
22     fun1(myclass);
23     cout<<" the initial value of class:a after fun1:  "<<myclass.a<<'\n';
24     myclass.a=10;
25     fun2(&myclass);
26     cout<<" the initial value of class:a after fun2:  "<<myclass.a<<'\n';
27     myclass.a=10;
28     fun3(myclass);
29     cout<<" the initial value of class:a after fun3:  "<<myclass.a<<'\n';
30     system("pause");
31 }
32 void fun1(MyClass mc)
33 {
34     mc.a=40;
35     mc.method();
36 }
37 void fun2(MyClass* mc)
38 {
39     mc->a=60;
40     mc->method();
41 }
42 void fun3(MyClass&mc)
43 {
44     mc.a=80;
45     mc.method();
46 }

输出结果为

说明fun1没能改变a在main函数中的实际值,只是改变了传入参数的值。fun2和fun3都实现了a实际值的改变。

通过这点我们可以看出,不通过指针和引用才传递参数时,只是传递了值的拷贝,并未改变值原来的大小。

参照:http://www.cnblogs.com/wackelbh/archive/2009/12/29/1984064.html

 

posted on 2014-11-17 16:24  西瓜皮小队  阅读(608)  评论(0编辑  收藏  举报

导航