Complete the class Vec2 with operator+, operator-, operator* (by a whole number), operator== and operator<<, which prints (x, y). main reads two vectors and a number k and prints a + b, a - b, a * k and whether a == b.
What to build
A Vec2 class with arithmetic, comparison and printing operators.
Requirements
- Make
+,-and*return new vectors without changing their operands. - Make
==compare both coordinates. - Write
operator<<to print(x, y).
Input
One line with x1 y1 x2 y2 k: the two vectors and the number (all from -1000 to 1000).
Output
Four lines: a + b, a - b, a * k, then equal or different.
Constraints
All values are from -1000 to 1000.
Example
Input:
1 2 3 4 2
Output:
(4, 6)
(-2, -2)
(2, 4)
different
Why it works
Each operator is a function call such as a.operator+(b), so the class decides exactly what each symbol means for vectors.
Examples
1 2 3 4 2
(4, 6) (-2, -2) (2, 4) different
5 5 5 5 0
(10, 10) (0, 0) (0, 0) equal
Hints
Hint 1
Each operator returns a new Vec2 and does not change its operands.
Hint 2
operator* takes an int: Vec2 operator*(int k) const.
Hint 3
operator<< prints (x, y).
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
class Vec2 {
int x, y;
public:
Vec2(int x, int y) : x(x), y(y) {}
Vec2 operator+(const Vec2& o) const { return Vec2(x + o.x, y + o.y); }
Vec2 operator-(const Vec2& o) const { return Vec2(x - o.x, y - o.y); }
Vec2 operator*(int k) const { return Vec2(x * k, y * k); }
bool operator==(const Vec2& o) const { return x == o.x && y == o.y; }
friend ostream& operator<<(ostream& out, const Vec2& v);
};
ostream& operator<<(ostream& out, const Vec2& v) {
out << "(" << v.x << ", " << v.y << ")";
return out;
}
int main() {
int x1, y1, x2, y2, k;
cin >> x1 >> y1 >> x2 >> y2 >> k;
Vec2 a(x1, y1), b(x2, y2);
cout << a + b << endl;
cout << a - b << endl;
cout << a * k << endl;
cout << (a == b ? "equal" : "different") << endl;
return 0;
}