ページ 11

オブジェクト指向エクササイズについて

Posted: 2015年9月29日(火) 12:55
by C#++
現在オブジェクト指向エクササイズをしています
その中のプロパティ禁止の練習をしています
クラスは5つです(Component Velocity Location X Y)
下記がソースになります

コード:

class X{
private:
	int value;
public:
	void incrementValue( X x ){
		//value += x.getValue();
	}
};
class Y{
private:
	int value;
public:
	void incrementValue( Y y ){
		//value += y.getValue();
	}
};
class Velocity{
private:
	X x;
	Y y;
public:
};
class Location{
private:
	X x;
	Y y;
public:
	void incrementX( Velocity velocity ){
		this->x.incrementValue( /*velocity.x*/ );
	}
	void incrementY( Velocity velocity ){
		this->y.incrementValue( /*velocity.y*/ );
	}
};
class Component{
private:
	Location location;
	Velocity velocity;
public:
	void Move(){
		this->location.incrementX( this->velocity );
		this->location.incrementY( this->velocity );
	}
};
int main(){
	Component *component = new Component();
	component->Move();
	return 0;
}
質問したい内容は「決まった速度で等速直線運動するコンポネントを作成するにはどうしたらいいのか」です。
ゲッターありで書いた場合には下記の通りになると予想しています

コード:

class X{
private:
	int value;
public:
	void incrementValue( X x ){
		value += x.getValue();
	}
	int getValue(){
		return this->value;
	}
};
class Y{
private:
	int value;
public:
	void incrementValue( Y y ){
		value += y.getValue();
	}
	int getValue(){
		return this->value;
	}
};
class Velocity{
private:
	X x;
	Y y;
public:
	X getX(){	return this->x;	}
	Y getY(){	return this->y;	}
};
class Location{
private:
	X x;
	Y y;
public:
	void incrementX( Velocity velocity ){
		this->x.incrementValue( this->x );
	}
	void incrementY( Velocity velocity ){
		this->y.incrementValue( this->y );
	}
};
class Component{
private:
	Location location;
	Velocity velocity;
public:
	void Move(){
		this->location.incrementX( this->velocity );
		this->location.incrementY( this->velocity );
	}
};
int main(){
	Component *component = new Component();
	component->Move();
	return 0;
}
みなさんならこの問題どう解決しますか?

Re: オブジェクト指向エクササイズについて

Posted: 2015年10月01日(木) 23:49
by Poco
「決まった速度で等速直線運動するコンポネントを作成するにはどうしたらいいのか」であれば、
私ならComponentクラスに速度と座標をint型で持たせて、他のクラスは作成しません。

コード:

class Component{
private:
	int x;
	int y;

	int vx;
	int vy;
public:
	Component(int x, int y, int vx, int vy) : x(x), y(y), vx(vx), vy(vy){}

	void Move(){
		x += vx;
		y += vy;
	}
};