1. 程式人生 > >C++快速入門---傳值、傳值和傳引用(6)

C++快速入門---傳值、傳值和傳引用(6)

C++快速入門---傳值、傳值和傳引用(6)

 

 

傳值

#include <iostream>

void changeAge(int age, int newAge);

// 如果想要實現計劃功能,需要怎麼改?

main()
{
	int age = 24;
	std::cout << "My age is " << age << "\n";
	
	changeAge(age, age+1);
	
	std::cout << "Now my age is " << age << "\n";	
}

void changeAge (int age, int newAge)
{
	age = newAge;
	std::cout << "In this , my age is " << age << "\n";
}

 

 

傳地址

#include <iostream>

void changeAge(int *age, int newAge);

// 如果想要實現計劃功能,需要怎麼改?

main()
{
	int age = 24;
	std::cout << "My age is " << age << "\n";
	
	changeAge(&age, age+1);
	
	std::cout << "Now my age is " << age << "\n";	
}

void changeAge (int *age, int newAge)
{
	*age = newAge;
	std::cout << "In this , my age is " << *age << "\n";
}

交換: 

#include <iostream>

void swap(int *x, int *y);

main()
{
	int x, y;
	
	std::cout << "請輸入兩個不同的值:";
	std::cin >> x >> y;
	
	swap(&x, &y);
	
	std::cout << "調換後輸出:" << x << ' ' << y << "\n\n";
}

void swap(int *x, int *y)
{
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
}

 另一種交換方式:

#include <iostream>

void swap(int *x, int *y);

main()
{
	int x, y;
	
	std::cout << "請輸入兩個不同的值:";
	std::cin >> x >> y;
	
	swap(&x, &y);
	
	std::cout << "調換後輸出:" << x << ' ' << y << "\n\n";
}

void swap(int *x, int *y)
{
	*x = *x + *y;
	*y = *x - *y;
	*x = *x - *y;
}

另一種交換方式:

#include <iostream>

void swap(int *x, int *y);

main()
{
	int x, y;
	
	std::cout << "請輸入兩個不同的值:";
	std::cin >> x >> y;
	
	swap(&x, &y);
	
	std::cout << "調換後輸出:" << x << ' ' << y << "\n\n";
}

void swap(int *x, int *y)
{
	*x ^= *y;
	*y ^= *x;
	*x ^= *y;
}