编程语言
首页 > 编程语言> > C++参数传递

C++参数传递

作者:互联网

一、函数间参数传递的三种方式

1、值传递

主调函数:swap(x,y);

被调函数:void swap(int a,int b);

值传递特点分析:

2、引用传递

主调函数:swap(x,y);

被调函数:void swap(int &a,int &b);

引用传递特点分析:

3、指针传递

主调函数:swap(&x,&y);

被调函数:void swap(int *a,int *b);

指针传递特点分析:

下面为三种参数传递的实列

 

 

 1 #include <iostream>
 2 
 3 void swap1(int a, int b)
 4 {
 5     int t;
 6     t = a; a = b; b = t;
 7 }
 8 void swap2(int &a, int &b)
 9 {
10     int t;
11     t = a; a = b; b = t;
12 }
13 void swap3(int *a, int *b)
14 {
15     int t;
16     t = *a; *a = *b; *b = t;
17 }
18 
19 int main()
20 {
21     std::cout << "Exchange x and y." << std::endl;
22     int x1 = 5, y1 = 10;
23     int x2 = 5, y2 = 10;
24     int x3 = 5, y3 = 10;
25     swap1(x1,y1);
26     swap2(x2, y2);
27     swap3(&x3, &y3);
28     std::cout << x1 << "," <<y1 << std::endl;
29     std::cout << x2 << "," << y2 << std::endl;
30     std::cout << x3 << "," << y3 << std::endl;
31     return 0;
32 }
33 //输出结果
34 Exchange xand y.
35 5, 10
36 10, 5
37 10, 5
View Code

 

 

 

#include <iostream>

void swap1(int a, int b)
{
    int t;
    t = a; a = b; b = t;
}
void swap2(int &a, int &b)
{
    int t;
    t = a; a = b; b = t;
}
void swap3(int *a, int *b)
{
    int t;
    t = *a; *a = *b; *b = t;
}

int main()
{
    std::cout << "Exchange x and y." << std::endl;
    int x1 = 5, y1 = 10;
    int x2 = 5, y2 = 10;
    int x3 = 5, y3 = 10;
    swap1(x1,y1);
    swap2(x2, y2);
    swap3(&x3, &y3);
    std::cout << x1 << "," <<y1 << std::endl;
    std::cout << x2 << "," << y2 << std::endl;
    std::cout << x3 << "," << y3 << std::endl;
    return 0;
}

Exchange xand y.
5, 10
10, 5
10, 5

标签:传递,函数,int,void,主调,C++,参数传递,实参
来源: https://www.cnblogs.com/qlzstudy/p/16456194.html