overloading ostream issue
Oct 9, 2019 at 6:57pm UTC
Hi I got this of a youtube video but I can't get it to compile, can anybody tell me what is wrong and teach me a bit about overloading the ostream operator? I think the problem is lines 32-36. thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#include<iostream>
#include<string>
struct Vector2
{
float x, y;
Vector2(float x, float y)
: x(x), y(y) {}
Vector2 Add(const Vector2& other) const
{
return Vector2(x + other.x, y + other.y);
}
Vector2 operator +(const Vector2& other) const
{
return Add(other);
}
Vector2 Multiply(const Vector2& other) const
{
return Vector2(x * other.x, y * other.y);
}
Vector2 operator *(const Vector2& other) const
{
return Multiply(other);
}
};
std::ostream& operator <<(std::string& ostream, const Vector2 & other)
{
stream << other.x << ", " << other.y;
return stream;
}
int main()
{
Vector2 position(4.0f, 4.0f);
Vector2 speed(0.5f, 1.5f);
Vector2 powerup(1.1f, 1.1f);
Vector2 result1 = position.Add(speed.Multiply(powerup));
Vector2 result2 = position + speed * powerup;
std::cout<<result2<<std::endl;
return 0;
}
Oct 9, 2019 at 7:00pm UTC
You're trying to overload an ostream& so your first parameter should be an ostream& not a std::string&
Oct 9, 2019 at 7:27pm UTC
Thanks that helped a lot, now what should I replace stream with as that is producing the error "stream was not declared in this scope"?
Thanks.
Oct 9, 2019 at 7:30pm UTC
What did you name the ostream& parameter? Maybe use that?
Oct 9, 2019 at 9:00pm UTC
Thanks for your invaluable help, got it to compile :-)
Topic archived. No new replies allowed.