Please consider the following code:
#include <iostream>
using namespace std;
class vec {
public:
float x,y;
vec(float a, float b) {
x = a;
y = b;
}
const vec operator + (const vec & a) {
vec ResVec(0.0f, 0.0f);
ResVec.x = x + a.x;
ResVec.y = y + a.y;
return ResVec;
}
};
vec foo(const vec& v1, const vec& v2)
{
const vec temp(2.0f,2.0f);
return v1 + v2 + temp;
}
int main() {
vec v1(1.0f, 1.0f);
vec v2(2.0f,2.0f);
vec v3(0.0f,0.0f);
v3 = foo(v1,v2);
}
I want to implement the function foo with const input parameters. But I fail, because the compiler says: error: no match for ‘operator+’ (operand types are ‘const vec’ and ‘const vec’)
return v1 + v2 + temp. How can I modify the operator overloading so that I can use the + operator in the function
vec foo(const vec& v1, const vec& v2)
const vec operator + (const vec & a)toconst vec operator + (const vec & a) const. It tells the compiler that this function does not change anything about the object from that it is called and then it can be called forconstobjects.