1

I've recently tried operator overloading, and have looked at this stackoverflow page (http://stackoverflow.com/questions/4421706/operator-overloading) about operator overloading.

I have overloaded the * operator and can run code such as

Vector2 a(2, 3);
Vector2 b(5, 8);
Vector2 c = a*b;

but get the compile time error error: invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'Vector2')

When running code such as

std::cout << a*b;

Here is Vector2.cpp

#include "Vector2.h"

Vector2::Vector2(const float x, const float y) {
    this->x = x;
    this->y = y;
}

Vector2 &Vector2::operator*=(const Vector2 &rhs) {
    this->x *= rhs.x;
    this->y *= rhs.y;
    return *this;
}

std::ostream &operator<< (std::ostream &out, Vector2 &vector) {
    return out << "(" << vector.x << ", " << vector.y << ")";
}

and here is Vector2.h

#include <iostream>

class Vector2 {
    public:
        float x;
        float y;

        Vector2(const float x, const float y);
        Vector2 &operator*=(const Vector2 &rhs);
};

inline Vector2 operator*(Vector2 lhs, const Vector2 &rhs) {
    lhs *= rhs;
    return lhs;
}

std::ostream &operator<<(std::ostream &out, Vector2 &vector);

I'm not sure where to go from here.

rabbidrabbit
  • 420
  • 5
  • 13

2 Answers2

6

The problem is that

a*b

returns a temporary, so you need:

std::ostream &operator<<(std::ostream &out, const Vector2 &vector);
//                                            |
//                                      notice const                                                  

as a temporary can't bind to a non-const reference.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

The following should work:

Vector2 c = a*b;
std::cout << c;
Hakan Serce
  • 11,198
  • 3
  • 29
  • 48