Reputation: 23
I'm trying to overload some operators for my Vector class, but is getting below error when trying to to assert(v+v == v*2):
[Error] no match for 'operator==' (operand types are 'Vector' and 'Vector').
When using assert(v==v) the function works fine, and I'm also able to create new vectors using the + and * operator.
class Vector{
private:
vector<double> arr;
friend bool operator ==( Vector &src, Vector &src2) {
int z = src.size();
if (z != src2.size()){
return false;
}
for (int i = 0; i < src.size(); i++){
double p = src.at(i);
if (p != src2.at(i)){
return false;
}
};
return true;
};
friend Vector operator +(Vector &src, Vector &src2) {
Vector TEMP = src;
for (int i = 0; i < src.size(); i++){
TEMP.arr[i] = src.arr[i] + src2.arr[i];
}
return TEMP;
};
friend Vector operator *(Vector &src, const int x) {
Vector TEMP = src;
for (int i = 0; i < src.size(); i++){
TEMP.arr[i] = src.arr[i] *x;
}
return TEMP;
};
};
int main() {
double data1[] = {3.4, 4.4, 6.0};
Vector v(sizeof(data1)/sizeof(double), data1);
assert(v == v);
assert(v + v == v * 2);
};
Upvotes: 2
Views: 69
Reputation: 173024
You declare the parameter type of operator ==
as lvalue reference to non-const. But both operator +
and operator *
return by value, what they return are rvalues; which can't be bound to lvalue reference to non-const.
You can change the parameter type of operator==
to lvalue reference to const, which could bind to rvalues. (And they don't need to be lvalue reference to non-const, because operator==
is not supposed to perform modification.) e.g.
friend bool operator ==(const Vector &src, const Vector &src2) {
...
}
Upvotes: 3