简体   繁体   中英

How to use function with parameters in class , c++?

I have to sum of two matrices (tridiagonal), everything works, but I don't know how to call function sum in main. I tried but it reports an error. Any help or recommendations would be appreciated.

.h:

class matrix
{
public:
matrix();
~matrix();
matrix(int i, int j);

void insert();
void iz();
void sum(matrix m1, matrix m2);

private:
int i;
int j;
vector<vector<int> > v;
};

.cpp

matrix::matrix()
{
}


matrix::matrix()
{
}

matrix::matrix(int i, int j){
v.resize(i);
for (int k = 0; k < i; k++)
    v[k].resize(j);
this->i = i;
this->j = j;
}


void matrix::insert()
{
  int x;
  for (int a = 0; a < i; a++){
    for (int b = 0; b < j; b++){
        if (abs(a-b) <= 1){
            x = rand() % 100+1;
            v[a][b] = x;
        }
        else
            v[a][b] = 0;
     }
    }
    }

void matrix::iz()
{
 for (int a = 0; a < i; a++){
    for (int b = 0; b < j; b++)
        cout << v[a][b] << " ";
    cout << endl;
 }

}

void matrix::sum(matrix m1, matrix m2)
{
  matrix m3;
  int c = m1.i;
  int d = m1.j;
  if (m1.i == m2.i && m1.j == m2.j)
  {
    for (int a = 0; a < c; a++)
    {
        for (int b = 0; b < d; b++){
            m3.v[a][b] = m1.v[a][b] + m2.v[a][b];
        }
        cout << endl;
      }
  }
  else
    cout << "Error" << endl;
   }

main

matrix m1(6, 6);
m1.insert();
m1.iz();
cout << endl << endl;

matrix m2(6, 6);
m2.insert();
m2.iz();

Here is the problem:

/*
matrix m3;
m3.sum(m1, m2);
m3.iz();
*/

cin.ignore();
cin.get();

return 0;

The problem lies in the sum function where you create a new object matrix m3, and perfor the addition on that object, instead of this.

Do: this->v[a][b] = m1.v[a][b] + m2.v[a][b];

instead of: m3.v[a][b] = m1.v[a][b] + m2.v[a][b];

Also, you need to set the this->i and this->j variables to m1.i and m1.j , plus you should also do all your resizing of this->v too.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM