-
February 13th, 2013, 06:04 PM
#1
Adding two objects of class "Matrix"
I am trying to add matrices a and b. I am getting an error in the "add" function, probably because I have m[i] in it, and m is not an array. What is the correct way of writing the "add" member function here?
Also, although the "read" and "write" member functions of the class are working just fine, do you think there is a better way of writing them?
Code:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const int rows=3;
const int columns=3;
class Matrix
{
private:
double data[rows*columns];
public:
Matrix();
void add(const Matrix&);
void read();
void write();
};
Matrix::Matrix(){
for(int i=0;i<rows*columns;i++)
{
data[i]=0;
}
}
//ADD
void Matrix::add(const Matrix&m)
{
for(int i=0;i<rows*columns;i++)
{
data[i]+=m[i];
}
}
//READ
void Matrix::read()
{
int l=0;
double array[rows][columns];
for(int i=0;i<rows;i++)
{
cout<<endl;
for(int j=0;j<columns;j++)
{
cin>>array[i][j];
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
data[l++]=array[i][j];
}
}
}
//WRITE
void Matrix::write()
{
double array[rows][columns];
int k=0;
for(int i=0;i<rows;i++)
{
for(int j=0; j < rows; j++)
{
array[i][j] =data[k++];
}
}
for (int i=0; i<rows; i++)
{
for (int j=0; j<columns; j++)
{
cout << setw(10) << array[i][j];
}
cout << endl;
}
}
void menu();
int main(){
cout.setf(ios::showpoint|ios::fixed);
cout.precision(3);
Matrix a,b;
cout<<"Enter 9 elements of A"<<endl;
a.read();
cout<<"Enter 9 elements of B"<<endl;
b.read();
cout<<"A is: "<<endl;
a.write();
cout<<endl<<"B is: "<<endl;
b.write();
cout<<"A+B= "<<endl;
a.add(b);
cout<<endl<<endl;
return 0;
}
-
February 13th, 2013, 08:04 PM
#2
Re: Adding two objects of class "Matrix"
Originally Posted by math8
I am trying to add matrices a and b. I am getting an error in the "add" function, probably because I have m[i] in it, and m is not an array. What is the correct way of writing the "add" member function here?
There is no such thing as [] for the Matrix class. That's why you get an error.
The array inside of Matrix is the member you want to use.
Regards,
Paul McKenzie
-
February 13th, 2013, 08:28 PM
#3
Re: Adding two objects of class "Matrix"
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|