2012-05-25 65 views
1

时出现错误我最近尝试了运算符重载,并且已经查看了关于运算符重载的这个stackoverflow页面(http://stackoverflow.com/questions/4421706/operator-overloading)。使用重载的运算符<< with operator *

我重载*运算和当运行代码,如

std::cout << a*b; 

这里可以运行代码,如

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

,但得到的编译时错误error: invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'Vector2')

是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 << ")"; 
} 

这里是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); 

我不知道在哪里可以从这里走。

+0

你检查使用括号:'COUT <<(A * B)'? – betabandido

+0

是的,这是我尝试的第一件事,但它没有奏效。 – rabbidrabbit

+1

下面是证明为什么不能:http://en.cppreference.com/w/cpp/language/operator_precedence – chris

回答

6

的问题是,

a*b 

返回一个临时的,所以你需要:

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

作为临时不能绑定到一个非const引用。

+1

第二点,为什么?他拥有的方式非常完美。无论如何,你必须复制对象,为什么不在参数列表中做? –

+0

谢谢,这很有道理。 – rabbidrabbit

+0

@BenjaminLindley为什么复制到对象? –

0

下面应该工作:

Vector2 c = a*b; 
std::cout << c; 
+0

是的,确实有效。我想要做的是做std :: cout << a * b; – rabbidrabbit

+0

然后,您应该更新运算符签名,以便像其他人所建议的那样采用const参数。 –