时出现错误我最近尝试了运算符重载,并且已经查看了关于运算符重载的这个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);
我不知道在哪里可以从这里走。
你检查使用括号:'COUT <<(A * B)'? – betabandido
是的,这是我尝试的第一件事,但它没有奏效。 – rabbidrabbit
下面是证明为什么不能:http://en.cppreference.com/w/cpp/language/operator_precedence – chris