我试图建立一个
SquareMatrix
通过使用接受4个参数作为4个子矩阵的构造函数来创建模板类
a
,
b
,
c
,
d
占据四个象限(
一
=西北,
b
=东北,
c
=西南,
d
=东南)。如下所示:
template<class T> class SquareMatrix {
public:
SquareMatrix(){}
SquareMatrix(const T first, const T second, const T third, const T fourth) {
a = first;
b = second;
c = third;
d = fourth;
}
SquareMatrix<T>(const SquareMatrix<T>& rhs) { // copy constructor
a = rhs.getA();
b = rhs.getB();
c = rhs.getC();
d = rhs.getD();
}
SquareMatrix& operator=(const SquareMatrix rhs) { // assignment operator
if (&rhs != this) {
SquareMatrix(rhs);
}
return *this;
}
~SquareMatrix() {} // destructor
// getters and setters
T getA() const {return a;}
T getB() const {return b;}
T getC() const {return c;}
T getD() const {return d;}
void setA(const T& input) {a = input;}
void setB(const T& input) {b = input;}
void setC(const T& input) {c = input;}
void setD(const T& input) {d = input;}
private:
// 4 quadrants
// [a, b;
// c, d]
T a, b, c, d;
};
template<class T> SquareMatrix<T> operator+(const SquareMatrix<T> lhs,
const SquareMatrix<T>& rhs) {
SquareMatrix<T> ret(lhs);
ret.setA( ret.getA() + rhs.getA() );
ret.setB( ret.getB() + rhs.getB() );
ret.setC( ret.getC() + rhs.getC() );
ret.setD( ret.getD() + rhs.getD() );
return ret;
};
template<class T> SquareMatrix<T> operator-(const SquareMatrix<T> lhs,
const SquareMatrix<T>& rhs) {
SquareMatrix<T> ret(lhs);
ret.setA( ret.getA() - rhs.getA() );
ret.setB( ret.getB() - rhs.getB() );
ret.setC( ret.getC() - rhs.getC() );
ret.setD( ret.getD() - rhs.getD() );
return ret;
};
// this is the implementation of Strassen's algorithm
template<class T> SquareMatrix<T> operator*(const SquareMatrix<T>& lhs,
const SquareMatrix<T>& rhs) {
T product_1 = lhs.getA() * ( rhs.getB() - rhs.getD() );
T product_2 = ( lhs.getA() + lhs.getB() ) * rhs.getD();
T product_3 = ( lhs.getC() + lhs.getD() ) * rhs.getA();
T product_4 = lhs.getD() * ( rhs.getC() - rhs.getA() );
T product_5 = ( lhs.getA() + lhs.getD() ) * ( rhs.getA() + rhs.getD() );
T product_6 = ( lhs.getB() - lhs.getD() ) * ( rhs.getC() + rhs.getD() );
T product_7 = ( lhs.getA() - lhs.getC() ) * ( rhs.getA() + rhs.getB() );
SquareMatrix<T> ret;
ret.setA(product_5 + product_4 - product_2 + product_6);
ret.setB(product_1 + product_2);
ret.setC(product_3 + product_4);
ret.setD(product_1 + product_5 - product_3 - product_7);
return ret;
};
现在,我试图通过以下操作创建一个嵌套的4x4矩阵:
int main() {
cout << "Example: a 4x4 matrix: " << endl;
// 4 single quadrants
SquareMatrix<int> M_1A(1, 2, 3, 4);
SquareMatrix<int> M_1B(5, 6, 7, 8);
SquareMatrix<int> M_1C(9, 10, 11, 12);
SquareMatrix<int> M_1D(13, 14, 15, 16);
// 4x4 matrix M_1
SquareMatrix< SquareMatrix<int> > M_1(M_1A, M_1B, M_1C, M_1D);
// test
cout << "test: " << endl;
cout << M_1.getA().getA() << endl;
return 0;
}
预期的矩阵输出应为
M_1 = [1,2,5,6; 3,4,7,8; 9,10,13,14; 11,12,15,16]
.
我用
M_1.getA().getA()
首次访问命令
M_1A
然后访问
1
嵌套在里面,但输出显示一个不断变化的大数字,也许是一个地址?(上次我尝试时,结果为6684672)。
是否有方法以这种方式实现矩阵类?
(编辑:现在包括赋值运算符和析构函数,可能是错误的来源)