時出現錯誤我最近嘗試了運算符重載,並且已經查看了關於運算符重載的這個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