Overloading Operators

Pages: 12
Hey guys,

New to the forums here. I'm a student taking C++ and need some help with an overloaded method. I've tried looking up everything but confused. Maybe someone here can shed some light on my problem

I have a class that dynamically allocates a 2d array. This array is like a matrix holding doubles. The problem i'm having is with the header file and cpp file associated with the class.

I need to overload the method * and multiply the 2d array. Here is a few parts of it:

My Header file::
1
2
3
4
5
6
7
8
9
10
11
12
13
 
class Matrix
{
 public:
   Matrix(); //Default Constructor
   //cut out some of my functions that aren't necessary for this problem
   Matrix operator*(const Matrix& a1, const double vector);
 private:     
   void initialize(); //initializes the matrix to 0;
   double **arrayMatrix;
   int row;
   int col;
};


My CPP code::
1
2
3
4
5
6
7
8
9
   
Matrix Matrix::operator*(const Matrix& a1, const double vector)
   {
       for(int i = 0; i < row; i++){
           for(int j = 0; j < col; j++){
               arrayMatrix[i][j] = arrayMatrix[i][j] * vector;  //multiply the matrix by vector         
           }
       }         
    }


I'm getting the following errors:
16 Matrix.h `void Matrix::operator*(const Matrix&, double)' must take either zero or one argument
102 Matrix.cpp `void Matrix::operator*(const Matrix&, double)' must take either zero or one argument
Last edited on
Hi,

Instead of overloading * in your way
Matrix operator*(const Matrix& a1, const double vector);

you need to define it following way

Matrix operator*(const double vector)

each overload function of type( +, - , * , / , or == and so on ) has the current object this as it first parameter.

And the function must return an object of type Matrix, in most case a temporary object which holds the result

so your code should be like following

1
2
3
4
5
6
7
8
9
10
11
12
13
class Matrix
{
 public:
   Matrix(); //Default Constructor
    Matrix(int rowSize, int colSize); 
   //cut out some of my functions that aren't necessary for this problem
   Matrix operator*( const double vector);
 private:     
   void initialize(); //initializes the matrix to 0;
   double **arrayMatrix;
   int row;
   int col;
};


and CPP file

1
2
3
4
5
6
7
8
9
10
Matrix Matrix::operator*(const double vector)
   {
       Matrix tmp( row, col ) ;
       for(int i = 0; i < row; i++){
           for(int j = 0; j < col; j++){
               tmp.arrayMatrix[i][j] = arrayMatrix[i][j] * vector;  //multiply the matrix by vector         
           }
       }
   return tmp;        
    }



You should also implments copy-constructor Matrix(const Matrix& other ) , assigment operator = operator and destructor ~Matrix()

Hope it helps
Last edited on
I have a destructor , haven't gotten to the assignment operator yet or copy-constructor..

I ran into some problems with your code.

[Linker error] undefined reference to `operator*(Matrix const&, double)'

Never mind on the error, forgot i had to recompile all o.0
Last edited on
Actually getting a crash when running your code... here is the use of those functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main(int argc, char *argv[])
{
    Matrix t1(5, 5);

    double count = 1;

    //put some numbers in the matrix
    for(int i = 0; i < 5; i++){
      for(int j = 0; j < 5; j++){     
         t1.set_element(i, j, count);
         count++;

      }
   }
       
    t1 = t1*3;
    t1.printMatrix();
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
Got it ;)

figured i needed the assignment operator which i just created to make this work!

Thanks a ton!
If your class has any dynamic members, let say it here **arrayMatrix, so you have to implement assigment operator, copy constructor and destructor, otherwise it wont work.

a possible assigment operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Matrix& operator=( const Matrix& other ){
    if( this == &other )
		return *this; 
   if( row != other.getRow() || col != other.getCol() ){
            clean() ; //  it is the destructor, implement it to destroy the current object
             row = other.getRow();// you should implement getters
             col   = other.getCol(); //
            arrayMatrix= new double*[  row ];
	for(int i = 0 ; i < row ; i++){
		arrayMatrix[i] = new double[ col];
    }
     // here a copy values
      for(int i = 0; i < row; i++)
           for(int j = 0; j < col; j++)
          arrayMatrix[i][j] = other[i][j]; // [] operator should be implemented as well
    return *this;
}


And about the error change the method param to double vector, it should work than

Matrix operator*(double vector)

and it should be this way, the safer way
t1 = t1* (double )3;
Last edited on
Thanks, question on making an operator multiplication of another class member
header file:
Matrix operator*(const Matrix test);

This is to multiply 2 matrices
cpp:

1
2
3
4
5
6
7
    Matrix Matrix::operator*(const Matrix test)
{
    Matrix tmp(row, test.num_cols());
     //some code here
    return tmp;
}
 

are you asking a question or giving the answer ? excuse me I do not understand you.
Last edited on
The above code doesn't work, trying to figure out why

I'm trying to computer

matrix = matrix1 * matrix2
I have the logic for the computation, just getting syntax errors with the operator overloading

Error messages:
[Linker error] undefined reference to `Matrix::Matrix(Matrix const&)'
Use reference

header file:

Matrix operator*(const Matrix& test);

CPP:

1
2
3
4
5
Matrix Matrix::operator*(const Matrix& test){

// do some thing 

}


by the way which compiler and which IDE do you use ?
using Dev C++ , not sure which compiler it uses

but as for the code you supplied, its not working for me :(
some compiler behaves differen, so what I see from the error, your compiler wants you to define the function as following


header file:

Matrix operator*( Matrix const& test);

instead of

Matrix operator*(const Matrix& test);

and in cpp:

1
2
3
Matrix Matrix:: operator*( Matrix const& test){
// do some thing
}


instead of your current implementation


Last edited on
Thanks :)
Ok last and final need for some help...

I'm just not grasping this overloading :(

.h file
1
2
3
4
5
 public:
   Matrix(); //Default Constructor
   Matrix(int row, int col); //Constructor for 2 variables (rows and cols)
   ostream & operator<<(ostream &);
};


.cpp
1
2
3
4
5
6
7
8
9
   ostream& Matrix::operator<<(ostream & output){
    for(int i = 0; i < test.num_rows(); i++){
           for(int j = 0; j < test.num_cols(); j++){
                   output << test.mydata[i][j] << " " ;           
           }
    output << "\n";
    return output;   
   }


errors i'm getting :
19 Matrix.h ISO C++ forbids declaration of `ostream' with no type
19Matrix.h expected `;' before '&' token
Last edited on
Hi again,

declare your ostream & operator<<(ostream &); not as a member function but as normal function in your header just under your class Matrix as following

1
2
3
ostream& operator<<(ostream& out, const Matrix& test){
        //do some thing
}


or your compiler might wish some thing else :-) like following

1
2
3
ostream& operator<<(ostream& out, Matrix const& test){
        //do some thing
}


try it yourself
Last edited on
doing the above i got :

30 Matrix.h expected constructor, destructor, or type conversion before '&' token
30 Matrix.h expected `,' or `;' before '&' token
where did you declare and implement the function? It must not be inside the class, but outside of the class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Matrix{

   //do some thing
};


ostream& operator<<(ostream& out, const Matrix& test){
        //do some thing
}


// or depending on your compiler



ostream& operator<<(ostream& out, Matrix const& test){
        //do some thing
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Matrix
{
 public:
   Matrix(); //Default Constructor
   Matrix(int row, int col); //Constructor for 2 variables (rows and cols)
   //...more functions ...
 private:    
   //...some private functions ...
};

ostream& operator<<(ostream & output, const Matrix & test){
    for(int i = 0; i < test.num_rows(); i++){
         for(int j = 0; j < test.num_cols(); j++){
                   output << test.mydata[i][j] << " " ;           
           }
    output << "\n";
    return output;   
   }


errors:
30 Matrix.h expected constructor, destructor, or type conversion before '&' token
30 Matrix.h expected `,' or `;' before '&' token

line 30 points to
1
2
3
4
5
6
7
8
ostream& operator<<(ostream & output, const Matrix & test){ //line 30
    for(int i = 0; i < test.num_rows(); i++){
         for(int j = 0; j < test.num_cols(); j++){
                   output << test.mydata[i][j] << " " ;           
           }
    output << "\n";
    return output;   
   }

Last edited on
your class must implement the const version of num_rows , num_rows and operator []

like following

1
2
3
4
5
6
7
8
9
10
11
class Matrix{

public:

   int num_rows(){
   //do some thing
   }
   int num_rows() const{
   // do the same as the normal version of num_rows
    }
};


do the same thing for the two other methods too.
you dont have to implement the methods within the class, you can also implement them in your source file....
Last edited on
they were already declared const..

can you explain why i need to do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Matrix
{
 public:
   Matrix(); //Default Constructor
   Matrix(int row, int col); //Constructor for 2 variables (rows and cols)
   Matrix(const Matrix& other); //Copy constructor
   ~Matrix(); //Default Destructor
   int num_rows() const; //returns the number of rows 
   int num_cols() const; //returns the number of columns
   //.. some more stuff .. 
 private:
   // ... some stuff ...

};
Pages: 12