関数(様々な引数)

プログラム例 6.1] 関数(様々な引数)

/****************************/
/* 関数(様々な引数)       */
/*      coded by Y.Suganuma */
/****************************/
#include <iostream>

using namespace std;
			// クラス Complex
class Complex
{
	public :
		int x, y;
		Complex(int x1, int y1) {   // コンストラクタ
			x = x1;
			y = y1;
		}
};
			// 関数 func
int func(int x1, int &x2, const int *y1, int *y2, Complex z1, Complex *z2, int x3 = 10)
{
	x1     += 10;
	x2     += 10;
//	y1[0]   = 100;   // const 指定のため修正不可
	y2[0]   = 100;
	z1.x    = 1000;
	(*z2).x = 1000;
	return (x1 + x2 + x3);
}

int main()
{
	int a1 = 1, a2 = 2;
	int b1[] = {10, 20};
	int b2[] = {10, 20};
	Complex c1(1, 2);
	Complex *c2 = new Complex(1, 2);
	printf("a1 %d a2 %d b1[0] %d b1[1] %d b2[0] %d b2[1] %d c1.x %d c2.x %d\n", a1, a2, b1[0], b1[1], b2[0], b2[1], c1.x, (*c2).x);
	int r = func(a1, a2, b1, b2, c1, c2);
	printf("a1 %d a2 %d b1[0] %d b1[1] %d b2[0] %d b2[1] %d c1.x %d c2.x %d r %d\n", a1, a2, b1[0], b1[1], b2[0], b2[1], c1.x, (*c2).x, r);

	return 0;
}
		
(出力)
a1 1 a2 2 b1[0] 10 b1[1] 20 b2[0] 10 b2[1] 20 c1.x 1 c2.x 1
a1 1 a2 12 b1[0] 10 b1[1] 20 b2[0] 100 b2[1] 20 c1.x 1 c2.x 1000 r 33