I know this question has appeared lots of times here and on the internet, but even by searching on this site I can't overload the +
operator in myvec
class. The strange thing is that I can overload the =
operator, but as I write the declaration and definition of the operator +
, I get an error.
More specifically, I declare the operator as
myvec& myvec::operator+(const myvec& v, const myvec& w)
and the definition is
myvec& myvec::operator +(const myvec& v, const myvec& w)
{
int d = v.size();
myvec x(d);
for (int i = 0; i < d; i++) {
x(i) = v(i)+w(i);
}
return x;
}
In the following my little class:
#include <iostream>
#include <cmath>
using namespace std;
class myvec {
private:
int dimension;
double* data;
public:
myvec(int dim);
myvec(const myvec& v);
~myvec();
int size() const;
void Print();
double& operator ()(int i);
myvec& operator =(const myvec& v);
myvec& operator +(const myvec& v, const myvec& w);
};
myvec::myvec(int dim)
{
dimension = dim;
data = new double[dim];
for (int i = 0; i < dimension; i++) {
data[i] = 0.0;
}
}
myvec::myvec(const myvec& v)
{
int dimensione = v.size();
data = new double[dimensione];
for (int i = 0; i < dimensione; i++) {
data[i] = v.data[i];
}
}
myvec::~myvec()
{
dimension = 0;
delete[] data;
data = NULL;
}
int myvec::size() const
{
return dimension;
}
double& myvec::operator ()(int i)
{
return data[i];
}
myvec& myvec::operator =(const myvec& v)
{
int dim = v.size();
for (int i = 0; i < dim; ++i) {
data[i] = v.data[i];
}
return *this;
}
myvec& myvec::operator +(const myvec& v, const myvec& w)
{
int d = v.size();
myvec x(d);
for (int i = 0; i < d; i++) {
x(i) = v(i)+w(i);
}
return x;
}
void myvec::Print()
{
for (int i = 0; i < dimension; i++) {
cout << data[i]<<endl;
}
}
The compiler gives me the error:
testmyvec.cpp.cc:77:59: error: ‘myvec& myvec::operator+(const myvec&, const myvec&)’ must take either zero or one argument
It's clearly referring to the definition of the +
operator. How can I fix it in order to overload the operator?