I'm stuck with overloading operators "+", "-", "/" and "*" in my program. Basically I've got an object, which is dynamically allocated array of double values. I've got the whole program, but I can't get through those overloads.
my constructor looks like this:
table::table(int size) {
this->size = size;
tab = new double[size];
count++;
}
I've wrote something like that:
table & table::operator-(const table &tab3 )
{
table * tab_oper2 = new table(size);
for(int i=0; i< tab3.size; i++)
{
(*this).tab[i] -= tab3.tab[i];
}
return *this;
}
which generally works, but It's not generally good way to do it. My instructor told me to try to switch (*this) to *tab_oper2, return it as a reference but it doesn't work. Please, could someone tell me how to do it properly?
C++ is a value oriented language; return a table
(and not a table&
). Construct the return value in a local variable, and return it. And don't forget the rule of three: given the little code you've shown, you'll need a copy constructor, an assignment operator and a destructor. (Of course, if you use std::vector
, rather than new[]
, all of this will be taken care of for you.)
You should return a third object result
by value:
table table::operator-(const table &t) const
{
table result(size);
for(int i=0; i< t.size; i++)
{
result.tab[i] = this->tab[i] - t.tab[i];
}
return result;
}
operator -
is different from operator -=
which you was writing. When you're overloading operator-
you shouldn't manipulate this
.
You are allocating a result table but you are not populating it. Populate the result table and it will work.
table & table::operator-(const table &tab3 )
{
table * tab_oper2 = new table(size);
for(int i=0; i< tab3.size; i++)
{
tab_oper2->tab[i] = tab[i] - tab3.tab[i];
}
return *tab_oper2;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.