pokche - 11 months ago 40

C++ Question

I have two classes,

`my_matrix`

`my_vector`

`my_vector`

`my_matrix`

When I do

`my_matrix tmp = vec * mat`

`mat`

`my_matrix`

`vec`

`my_vector`

But when I do

`my_vector tmp = mat * vec`

no viable conversion from '' to '`my_matrix`

'`my_vector`

and this error in g++:

conversion from '' to non-scalar type '`my_matrix`

' requested`my_vector`

I think I know what the problem is. After

`mat`

`vec`

`my_matrix`

What do you think the solution for this would be?

I have tried defining

`void operator*(my_vector&, my_matrix&)`

`my_vector operator*(my_matrix&)`

`class my_matrix{`

public:

my_matrix operator*(my_matrix& other_mat){

my_matrix tmp(row, other_mat.col);

// for loop to matrix multiply that fill up the tmp

return tmp;

}

};

class my_vector:public my_matrix{

public:

// not sure if I need operator* here

// Somehow I want to bring the my_vector tmp = mat * vec; here so

// it would return vector instead of matrix

// I have tried : but not successful

// my_vector operator*(my_matrix&)

// void operator*(my_vector&, my_matrix&); (non member)

};

int main(){

my_matrix mat = {{1,2,3},{4,5,6}}; // 2x3

my_vector vec = {1,2,3}; // 3x1

my_vector tmp = mat * vec; // 2x3 * 3*1 gives 2x1 vector

}

Answer Source

Try something like this:

```
class my_matrix {
public:
my_matrix operator*(const my_matrix& other_mat) const {
my_matrix tmp(row, other_mat.col);
// for loop to matrix multiply that fill up the tmp
return tmp;
}
};
class my_vector : public my_matrix {
public:
using my_matrix::operator*;
my_vector operator*(const my_vector& other_vec) const {
my_vector tmp(...);
// for loop to vector multiply that fill up the tmp
return tmp;
}
};
my_vector operator*(const my_matrix &lhs, const my_vector &rhs)
{
my_vector tmp(...);
// for loop to vector multiply that fill up the tmp
return tmp;
}
int main() {
my_matrix mat = {{1,2,3},{4,5,6}}; // 2x3
my_vector vec = {1,2,3}; // 3x1
my_vector tmp = mat * vec; // 2x3 * 3x1 gives 2x1 vector
}
```