zoukankan      html  css  js  c++  java
  • 交换两个实参的值(c++)

    1. 引用

    #include <iostream>
    using namespace std;
    void swap( int &a, int &b )
    {
        int temp;
        temp=a; a=b; b=temp;
    }
    
    int main()
    {
        int x=3, y=5;
        cout<<" x= "<<x<<" y= "<<y<<endl;
        swap( x, y );
        cout<<" x= "<<x<<" y= "<<y<<endl;
        return 0;
    }
    

    2. 指针

    #include <iostream>
    using namespace std;
    void swap( int *a, int *b )
    {
        int temp;
        temp = *a;
        *a = *b;
        *b = temp;
    }
    
    int main()
    {
        int x=3, y=5;
        cout<<" x= "<<x<<" y= "<<y<<endl;
        swap( &x, &y );
        cout<<" x= "<<x<<" y= "<<y<<endl;
        return 0;
    }
    

    几个错误举例:

    错误示例1:(光改变形参是没有用的)

    #include <iostream>
    using namespace std;
    void swap( int a, int b )
    {
        int temp;
        temp=a; a=b; b=temp;
    }
    
    int main()
    {
        int x=3, y=5;
        cout<<" x= "<<x<<" y= "<<y<<endl;
        swap( x, y );
        cout<<" x= "<<x<<" y= "<<y<<endl;
        return 0;
    }
    

    错误示例2:(指针概念不清,不知道新定义的指针temp指向哪里)

    #include <iostream>
    using namespace std;
    void swap( int *a, int *b )
    {
        int *temp;
        *temp = *a;
        *a = *b;
        *b = *temp;
    }
    
    int main()
    {
        int x=3, y=5;
        cout<<" x= "<<x<<" y= "<<y<<endl;
        swap( &x, &y );
        cout<<" x= "<<x<<" y= "<<y<<endl;
        return 0;
    }
    

    错误示例3:(指针概念不清,交换了地址)

    #include <iostream>
    using namespace std;
    void swap( int *a, int *b )
    {
        int *temp;
        temp = a;
        a = b;
        b = temp;
    }
    
    int main()
    {
        int x=3, y=5;
        cout<<" x= "<<x<<" y= "<<y<<endl;
        swap( &x, &y );
        cout<<" x= "<<x<<" y= "<<y<<endl;
        return 0;
    }
    
  • 相关阅读:
    4.2 手指绘图
    Linux-linux常用操作
    gdb的使用
    时钟的函数
    动态链接库
    简单算法整理
    win的使用
    c语言格式化打印
    Symfony2 学习笔记之控制器
    Symfony2 学习笔记之系统路由
  • 原文地址:https://www.cnblogs.com/yuzilan/p/10626175.html
Copyright © 2011-2022 走看看