I\'m writing a Matrix type where I defined operations *, +, >>, << and so on. Co
ID: 3569079 • Letter: I
Question
I'm writing a Matrix type where I defined operations *, +, >>, << and so on. Compiling works fine but running does not. Is there something wrong here or what should I give in in the terminal when reading the matrices? Thankful for help!
#include <iostream>
struct Matrix{
int a; //element 1,1
int b; //1,2
int c; //2,1
int d; //2,2
};
Matrix operator+ (const Matrix A, const Matrix B)
{
Matrix e=A;
return e+B;
}
Matrix operator* (const Matrix A, const Matrix B)
{
Matrix C;
C.a=A.a*B.a+A.b*B.c;
C.b=A.a*B.b+A.b*B.d;
C.c=A.c*B.a+A.d*B.c;
C.d=A.c*B.b+A.d*B.d;
return C;
}
{
Matrix B;
B.a=A.a*s;
B.b=A.b*s;
B.c=A.c*s;
B.d=A.d*s;
return B;
}
Matrix operator* (const Matrix A, const double s)
{
Matrix B;
B.a=A.a*s;
B.b=A.b*s;
B.c=A.c*s;
B.d=A.d*s;
return B;
}
std::istream& operator>> (std::istream& is, Matrix& A)
{
char ch;
return is >> A.a >> ch >> A.b >> ch >> A.c >> ch >> A.d;
}
std::ostream& operator<< (std::ostream& os, const Matrix A)
{
return os << A.a << " " << A.b << " " << A.c << " " << A.d;
}
int main ()
{
Matrix A;
std::cin >> A;
Matrix B;
std::cin >> B;
double c;
std::cin >> c;
std::cout << A+B << ". " << A*B << ". " << c*A << ". " << B*c;
}
Explanation / Answer
#include <iostream>
struct Matrix{
int a; //element 1,1
int b; //1,2
int c; //2,1
int d; //2,2
};
Matrix operator+ (const Matrix A, const Matrix B)
{
Matrix add=A;
add.a += B.a;
add.b += B.b;
add.c += B.c;
add.d += B.d;
return add;
}
Matrix operator* (const Matrix A, const Matrix B)
{
Matrix C;
C.a=A.a*B.a+A.b*B.c;
C.b=A.a*B.b+A.b*B.d;
C.c=A.c*B.a+A.d*B.c;
C.d=A.c*B.b+A.d*B.d;
return C;
}
Matrix operator* (const double s, const Matrix A)
{
Matrix B;
B.a=A.a*s;
B.b=A.b*s;
B.c=A.c*s;
B.d=A.d*s;
return B;
}
Matrix operator* (const Matrix A, const double s)
{
Matrix B;
B.a=A.a*s;
B.b=A.b*s;
B.c=A.c*s;
B.d=A.d*s;
return B;
}
std::istream& operator>> (std::istream& is, Matrix& A)
{
return is >> A.a >> A.b >> A.c >> A.d;
}
std::ostream& operator<< (std::ostream& os, const Matrix A)
{
return os << A.a << " " << A.b << " " << A.c << " " << A.d;
}
int main ()
{
Matrix A;
std::cin >> A;
Matrix B;
std::cin >> B;
double c;
std::cin >> c;
std::cout << A+B << ". " << A*B << ". " << c*A << ". " << B*c;
}