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

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
C#++

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

#1

投稿記事 by C#++ » 9年前

現在オブジェクト指向エクササイズをしています
その中のプロパティ禁止の練習をしています
クラスは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;
}
みなさんならこの問題どう解決しますか?

Poco
記事: 161
登録日時: 14年前

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

#2

投稿記事 by Poco » 9年前

「決まった速度で等速直線運動するコンポネントを作成するにはどうしたらいいのか」であれば、
私なら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;
	}
};

閉鎖

“C言語何でも質問掲示板” へ戻る