Re: Writing operator functions
On 14 Mar 2007 11:05:35 -0700 in comp.lang.c++, "valerij"
<valerij.rozouvan@gmail.com> wrote,
How to write "operator +" and "operator =" functions in a class with
a defined constructor?
operator+ should usually be
T operator+(T const & t1, T const & t2)
{
T result(t1);
result += t2;
return result;
}
operator= depends on the requirements of your class, but usually
you just use operator= of each of the base classes and members.
(That is the compiler supplied operator= if you do not write one,
but unfortunately you have to write += yourself.)
operator+= is a lot like operator= except using += instead of =.
All the = operators (if you need them) should be members.
//code "tested" on Microsoft Visual C++ 6.0
Failure to upgrade to at least MSVC 7.x may be harmful to your sanity.
class DatArray {
public:
int rows, columns;
double **a;
std::vector<std::vector<double> > a;
DatArray::DatArray(int r, int c) {
DatArray::DatArray(int r, int c)
: a(r, std::vector<double>(c))
{ }
/*DatArray DatArray::operator + (double d1) {
int c1, c2;
for (c1 = 0; c1 < rows; c1++)
for (c2 = 0; c2 < columns; c2++) a[c1][c2] = a[c1][c2] + d1;
return *this;
}*/
DatArray & DatArray::operator += (double d1) {
for (int c1 = 0; c1 < a.size(); c1++)
for (int c2 = 0; c2 < a[c1].size(); c2++)
a[c1][c2] += d1;
return *this;
}