You need to overload the access operator for const objects as well, because the r.h.s of the expression result[i] = v1[1] / v2 [i]
will evaluate to:
v1.operator[](i) / v2.operator[](i)
and both v1 and v2 are of type const ArithmeticVector<T>&
which means that the compiler will try to find the operator[](int) const
for both of them (they are constant objects). When you overload the operator for const as advised in the answer above, you can re-use the code in the const operator and just call the operator in the non-const operator by casting away constness of the object. That way you don't have to think about what you implemented in one operator and port it to another, and you don't have to debug your code at two places. Here is the model of your problem (I don't have your implementation of ArithmeticVector, so you have to use the parts of it for your stuff):
template<typename T>
class ArithmeticVector;
template<typename T>
ArithmeticVector<T> operator / (
const ArithmeticVector<T>& v1,
const ArithmeticVector<T>& v2
);
template<typename T>
class ArithmeticVector
{
public:
// Your declaration
T& operator[](int i)
{
// Casting away constness allows code re-use.
return const_cast<ArithmeticVector&>(*this).operator[](i);
}
// Const declaration:
T& operator[](int i) const
{
// Put your operator code here.
}
friend ArithmeticVector<T> operator / <> (
const ArithmeticVector<T>& v1,
const ArithmeticVector<T>& v2
);
};
template<typename T>
ArithmeticVector<T> operator / (
const ArithmeticVector<T>& v1,
const ArithmeticVector<T>& v2
)
{
//ArithmeticVector<T> result(v1.size());
ArithmeticVector<T> result;
result[0]=v1[0]/v2[0];
return result;
};
int main(int argc, const char *argv[])
{
ArithmeticVector<int> v1, v2, v3;
v1 = v2 / v3;
return 0;
}
There is a great book of Scott Meyers "Effective C++" and there you can read a great description on constness of objects and access operators. There is an answer on SO, that talks about this.
You need to also take care to avoid a Floating Point Exception (division by zero), or SIGFPE, which will happen when v3[i] == 0
, which you can do either by stabilizing the result (you loose accuracy):
result[i] = v1[i] / (v2[I] + 1e-15)
or you introduce a test which slows down the divison significantly (like an if testing if v2[i] == 0
).