Teachers open the door but You must enter by yourself.

Open Media Lab.
オープンメディアラボ

オブジェクト指向
Object Oriented

オブジェクト指向プログラミングというキーワードが流行った時期がありましたが、その本質の1つは、変数のグループ化にあります。

構造体

2次元ベクトルの和を求める処理です。



void main(){
	double ax = 1.0;
	double ay = 0.0;
	double bx = 0.0;
	double by = 1.0;
	double cx;
	double cy;

	cx = ax + bx;
	cy = ay + by;
	printf("%f %f\n", cx, cy);
}

2次元ベクトルを構造体で実現してみましょう。



struct Vector2{
	double x;
	double y;
};

void main(){
	struct Vector2 a;
	struct Vector2 b;
	struct Vector2 c;

	a.x = 1.0;
	a.y = 0.0;
	b.x = 0.0;
	b.y = 1.0;

	c.x = a.x + b.x;
	c.y = a.y + b.y;
	printf("%f %f\n", c.x, c.y);
}

クラス

2次元ベクトルをクラスで実現してみましょう。



class Vector2{
public:
	double x;
	double y;	
};

void main(){
	Vector2 a;
	Vector2 b;
	Vector2 c;

	a.x = 1.0;
	a.y = 0.0;
	b.x = 0.0;
	b.y = 1.0;

	c.x = a.x + b.x;
	c.y = a.y + b.y;
	printf("%f %f\n", c.x, c.y);
}

メンバ関数を利用すれば、



class Vector2{
public:
	double x;
	double y;
	Vector2( double a, double b ){ x = a; y = b; }
	Vector2(){ }
	void sum( Vector2 a, Vector2 b ){
		x = a.x + b.x;
		y = a.y + b.y;
	}
	void print(){
		printf("%f %f\n", x, y );
	}

};

void main(){
	Vector2 a(2.0, 1.0);
	Vector2 b(1.0, 2.0);
	Vector2 c;
	
	c.sum( a, b );
	c.print();
}

課題

ベクトルの色々な変換をメンバ関数で実現してみましょう。


  1. ベクトルの定数倍
  2. ベクトルの外積

This site is powered by Powered by MathJax