//swaps.cpp -- swapping with references and with pointers
#include <iostream>


void swapr(int & a, int & b);
void swapp(int * p, int * q);
void swapv(int a, int b);


int main()
{
using namespace std;
int wallet1 = 300;
int wallet2 = 350;

cout << "wallet1 = $" << wallet1;  //300
cout << " wallet2 = $" << wallet2 << endl;  //350

cout << "Using references to swap contents:\n";
swapr(wallet1, wallet2);
cout << "wallet1 = $" << wallet1;  //350
cout << " wallet2 = $" << wallet2 << endl;  //300

cout << "Using pointers to swap contents again:\n";  
swapp(&wallet1, &wallet2);
cout << "wallet1 = $" << wallet1;  //300
cout << " wallet2 = $" << wallet2 << endl;  //350

cout << "Trying to use passing by value:\n";
swapv(wallet1, wallet2);
cout << "wallet1 = $" << wallet1;  //300
cout << " wallet2 = $" << wallet2 << endl;  //350
return 0;
}

void swapr(int & a, int & b)
{
int temp;

temp = a;
a = b;
b = temp;
}

void swapp(int * p, int * q)
{
int temp;

temp = *p;
*p = *q;
*q = temp;
}

void swapv(int a, int b)
{
int temp;

temp = a;
a = b;
b = temp;
}

 

小觀念:

void swapr(int & a, int & b) 可知是型式參數
觀念,呼叫函數swapr(wallet1, wallet2);
時,可知如果 int & a=wallet1;
a便是wallet1的型式參數,故會跟著改值

arrow
arrow
    全站熱搜

    布拉怡 發表在 痞客邦 留言(0) 人氣()