注册 登录
编程论坛 C++教室

一个让人糊涂的问题

hmsabc 发布于 2010-08-18 22:24, 529 次点击
程序代码:

#include <iostream>
using namespace std;

int main( )
{
    void sort(int x, int y, int z);                    //声明函数 sort
    int x,y,z;
    cin >> x >> y >> z;
    sort( x,y,z);
    system("pause");
    return 0;
}

void sort(int x,int y,int z)
{
    int temp;
    if( x > y) { temp = x;x = y;y = temp;}
    if( z < x) cout << z << ',' << x << ',' << y << endl;
    else if( z < y) cout << x << ',' << z << ',' << y << endl;
    else cout << x << ',' << y << ',' << z << endl;
}




#include <iostream>
using namespace std;

int main( )
{
    void sort(int a, int b, int c);                    //声明函数 sort
    int a,b,c;
    cin >> a >> b>> c;
    sort( a,b,c);
    system("pause");
    return 0;
}

void sort(int x,int y,int z)
{
    int temp;
    if( x > y) { temp = x;x = y;y = temp;}
    if( z < x) cout << z << ',' << x << ',' << y << endl;
    else if( z < y) cout << x << ',' << z << ',' << y << endl;
    else cout << x << ',' << y << ',' << z << endl;
}

   
    上面两段代码,大家应该看得很清楚,都是经过编译的,结果也一样。上面那一段,给人的感觉好像对 int x,y,z;三个数给予了重复定义,因为在主函数里定义了int x,y,z; 又在定义函数时,在函数参数里也有 int x,y,z; 请问这种情况到底算不算重复定义?我想应该不算,否则通不过编译,但这种写法跟下面的写法相比,究竟都是对的呢,还是存在什么问题?我觉得上面的写法让人犯糊涂,下面的写法要清楚一些。



[ 本帖最后由 hmsabc 于 2010-8-18 22:25 编辑 ]
5 回复
#2
zhoufeng19882010-08-18 22:32
void sort(int a, int b, int c);                    //声明函数 sort,a,b,c只在sort函数声明的域中有效,出了这个作用域就无效了。
C++ Primer里面有提到这个。
#3
hmsabc2010-08-18 22:50
程序代码:

//算了,我觉得还是用这种写法:

#include <iostream>
using namespace std;

int main( )
{
    void sort(int, int, int);                    //声明函数 sort
    int a,b,c;                                   //定义三个整型变量
    cin >> a >> b>> c;                           //输入三个整数
    sort( a,b,c);                                //调用 sort 函数
    system("pause");
    return 0;
}

void sort(int x,int y,int z)                     //定义 sort 函数
{
    int temp;
    if( x > y) { temp = x;x = y;y = temp;}                         //由小到大排序的算法
    if( z < x) cout << z << ',' << x << ',' << y << endl;
    else if( z < y) cout << x << ',' << z << ',' << y << endl;
    else cout << x << ',' << y << ',' << z << endl;
}


#4
ToBeOOP2010-08-18 23:33
不算重定义,他们的作用域不同.不过变量名最好不要样...
#5
weble2010-08-18 23:50
函数声明,只是引入一个函数名字:void sort(int, int, int)
参数名叫什么无所谓
#6
pangding2010-08-19 00:43
嗯,虽然作用域不一样,但人看的时候还是容易混。起不一样的名字,或者不给名字相对好一点。
1