参数传递问题

[复制链接]
 楼主| gxgclg 发表于 2012-7-24 21:36 | 显示全部楼层 |阅读模式
#include <iostream>
using
namespace std;
int x;
void funA(int
&,int );
void funB(int ,int
&);
void main()
{
   
int first;
   
int second=5;
     x
=6;//初始化全局变量
     
//int x=6;//重新定义变量x
    funA(first,second);
    cout
<<first<<"
"<<second<<"
"<<x<<endl;
    funB(first,second);
    cout
<<first<<"
"<<second<<"
"<<x<<endl;//只初始化全局变量x的值为什么不按照引用或者指针的方式传递,也能改变x在函数外面的值。
   
//cout<<first<<" "<<second<<" "<<x<<endl;//如果重新定义变量x,x值没有被改变。这是为什么?
}
/*void main()//第二种方式
{
    int first;
    int second=5;
    x=6;//初始化全局变量
    funA(first,second);
    cout<<first<<" "<<second<<" "<<x<<endl;
    {
        int x=9;
        funB(first,second);
        cout<<first<<" "<<second<<" "<<x<<endl;//这里既然x值为9
    }
    cout<<x<<endl;//那么这里为什么x值又变成20了?
}
*/
void funA(int
&a,int b)
{
   
int first;
    first
=b+12;
    a
=2*b;
    b
=first+4;
}
void funB(int u,int
&v)
{
   
int second;
    second
=x;
    v
=second+4;
    x
=u+v;//x的值被改变。
}
火箭球迷 发表于 2012-7-24 22:10 | 显示全部楼层
如果局部跟全局变量名一样就先选择局部变量,如果没有改变量就选择全局,
dfsa 发表于 2012-7-24 22:17 | 显示全部楼层
//只初始化全局变量x的值为什么不按照引用或者指针的方式传递,也能改变x在函数外面的值。
你这是全局变量啊,到哪都改变,main函数和其他函数都可以改变
//int x=6;//重新定义变量x
你这里是定义另外一个局部变量,这不叫重新定义
在main函数中打印出来的是这个局部变量的值,而不是定义的全局变量的那个"x"
您需要登录后才可以回帖 登录 | 注册

本版积分规则

177

主题

1653

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部

177

主题

1653

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部