C++学习笔记 13 操作符operator

#include <iostream>

class Vector2 {
public:
	float x, y;
public:
	Vector2(float x, float y): x(x), y(y) {}

	Vector2 Add(const Vector2& other) {
		//return *this + other;
		return operator+(other);
	}

	Vector2 operator+(const Vector2& other) {
		return Vector2(x + other.x, y + other.y);
	}

	bool operator==(const Vector2& other) {
		return x == other.x && y == other.y;
	}
	bool operator!=(const Vector2& other) {
		//return !operator==(other);
		return !(*this == other);
	}
};

//类似Java的toString
//重载 <<
std::ostream& operator<<(std::ostream& stream, const Vector2& other) {
	stream << other.x << " | " << other.y;
	return stream;
}

void testOperator() {
	Vector2 a(10.0f, 20.0f);
	Vector2 b(15.0f, 25.0f);
	Vector2 c = a + b;
	std::cout << c << std::endl;
}

int main() {
	testOperator();
	std::cin.get();
}
posted @ 2025-12-11 10:17  超轶绝尘  阅读(2)  评论(0)    收藏  举报