为派生类实施内部操作员

Implementing inner operator for derived class

本文关键字:施内部 操作员 派生      更新时间:2023-10-16

假设我有一个常规矩阵类,为此我已经实现了执行常规矩阵乘法的操作员 *。

这样的操作员具有以下签名:

Matrix operator*(const Matrix & ) const; 

我现在希望为代表3x3矩阵的继承类Matrix3实现另一个 *运算符。

它将具有以下签名:

Matrix3 operator*(const Matrix3 &) const;

我正在寻找实施此操作员的正确方法,以重新使用已经为基类编写的代码,并最大程度地降低成本(即复制)。

这应该可以正常工作:

// Either return base class
Matrix operator*(const Matrix3& other) const
{
    return Matrix::operator*(other);
}
// Or construct from a Matrix
Matrix3 operator*(const Matrix3& other) const
{
    return Matrix3(Matrix::operator*(other));
}
// Either construct the Matrix data in the Matrix3
Matrix3(const Matrix& other)
{
    // Initialize Matrix specifics
    // Initialize Matrix3 specifics
}
// Or pass the Matrix to it's base class so it can take care of the copy
Matrix3(const Matrix& other) : Matrix(other)
{
    // Initialize Matrix3 specifics
}