ぼく用あれこれまとめ

演算子オーバーロード

最終更新:

bokuyo

- view
管理者のみ編集可

operator/演算子オーバーロード


こんな感じ

//プレイヤーの座標クラス
#include <iostream>

class PlayerCoordinate
{
public:
	PlayerCoordinate operator+(const PlayerCoordinate& other);
	PlayerCoordinate& operator+=(const PlayerCoordinate& other);

	inline float GetX()const;
	inline float GetY()const;

	inline void SetX(float n);
	inline void SetY(float n);
	inline void SetXY(float s, float t);

private:
	float x, y;
};

//演算子オーバーロード
PlayerCoordinate PlayerCoordinate::operator+(const PlayerCoordinate& other)
{
	PlayerCoordinate temp;
	temp.x = x + other.x;
	temp.y = y + other.y;
	return temp;
}

//演算子オーバーロード
PlayerCoordinate& PlayerCoordinate::operator+=(const PlayerCoordinate& other)
{
	x += other.x;
	y += other.y;
	return *this;
}

inline float PlayerCoordinate::GetX()const
{
	return x;
}

inline float PlayerCoordinate::GetY()const
{
	return y;
}

inline void PlayerCoordinate::SetX(float n)
{
	x = n;
}

inline void PlayerCoordinate::SetY(float n)
{
	y = n;
}

inline void PlayerCoordinate::SetXY(float s, float t)
{
	SetX(s);
	SetY(t);
}

int main(){

	PlayerCoordinate c1, c2;
	c1.SetXY(1.56f, 2.5f);
	c2.SetXY(3.14f, 9.5f);

	c1 += c2;

	std::cout<< c1.GetX() <<std::endl;

	return 0;
}

  • operator++(int)でダミーのパラメータをかませて前置インクリメントと後置インクリメントを区別するからくりってどうなってんの?
記事メニュー
目安箱バナー