1,105,534 Community Members

operator overloading to add matrix

Member Avatar
jt241
Newbie Poster
1 post since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Well I'm relatively new to the forums and to C++. I'd like to overload + and = to add two matrices by being able to use Z=X+Y format.

Header file:

#ifndef HOMEWORK1_H 
#define HOMEWORK1_H 

class Matrix{
		
public:
	double **element;
	Matrix(int=3,int=3);
	~Matrix();
	double getelement(int,int); 
	void setelement(int, int,double);
	Matrix & operator+(const Matrix &, const Matrix &);
	Matrix & operator=(const Matrix & );
	
private:
	int r;
	int c;

	
};

#endif

Implementation code for operator+:

Matrix & Matrix::operator+( const Matrix&  s, const Matrix& t) //overloaded +
 {
       Matrix temp(3,3);
        for (int r=0;r<3;r++)
            for (int c=0;c<3;c++)
			{
				temp(r,c)=s.getelement(r,c)+ t.getelement(r,c)
			}
		return temp;
		
	}
Matrix & Matrix::operator=(const Matrix & q)
  {
		Matrix temp(3,3);
        for (int r=0;r<3;r++)
            for (int c=0;c<3;c++)
			 temp(r,c)=q.getelement(r,c);
		
		return *this;

	}

I believe one problem I have is too many parameters for operator+, but the only example my professor gave me had it with two parameters. I cut the implementation file down to the basic lines.

Thanks for whatever help possible.

Member Avatar
dkalita
Posting Pro in Training
402 posts since Sep 2009
Reputation Points: 110 [?]
Q&As Helped to Solve: 61 [?]
Skill Endorsements: 0 [?]
 
0
 
Matrix & operator+(const Matrix &, const Matrix &);

this is not the prototype for overloading binary operator.
The proper is

Matrix & operator+(const Matrix &);

The other operand for the operation is the calling object.

say

Matrix a, b, c;

c = a+b;

here the operator + is being invoked by the object a.
i.e. a.operator+(b)

U have to add the matrix b to a and return the sum which will get assigned to matrix c.


and what do expect the following statement to do???????????????

temp(r,c)=s.getelement(r,c)+ t.getelement(r,c)
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article