在两个 child 类 中使用基本乘法运算符

Using Base Multiplication Operator in two child classes

我正在尝试编写一个简单的 Matrix/Point class 库,我想使用基础 classes 乘法运算符将两个继承的 classes 相乘过载。

编辑 2 代码已还原为原始代码,供未来的旅行者使用:

#include <array>
#include <tuple>
#include <vector>


template <typename DataType, unsigned short NumberOfRows, unsigned short NumberOfColumns>
class GenericMatrix
{
public:

    GenericMatrix operator * (GenericMatrix const & rightHandSide)
    {
        //DO MATRIX MULTIPLICATION
        return GenericMatrix<DataType, NumberOfRows, NumberOfColumns>();
    }   
};


template <typename DataType>
class RotationMatrix2D : public GenericMatrix<DataType, 2, 2>
{   
};

template <typename DataType>
class Point2D : public GenericMatrix<DataType, 1, 2>
{    
};

int main()
{
    RotationMatrix2D<double> rotMatrix;
    Point2D<double> point;

    point * rotMatrix; //Error here

    return 0;
}

这让我可以利用一个点基本上只是一个矩阵这一事实。但是,我不断遇到编译器错误:

Error C2679 binary '*': no operator found which takes a right-hand operand of type 'RotationMatrix2D' (or there is no acceptable conversion)

我该如何解决这个问题?

您的问题源于您的运算符是针对特定 GenericMatrix 模板实例的。要了解发生了什么,您可以像这样扩展 Point2D 继承的运算符:

GenericMatrix<double, 1, 2> 
GenericMatrix<double, 1, 2>::operator*(const GenericMatrix<double, 1, 2>& rhs)

现在,RotationMatrix2D<double>GenericMatrix<double, 2, 2> 不适合作为 rightHandSide 的参数,GenericMatrix<double, 1, 2>GenericMatrix<double, 2, 2> 是不同的不相关类型。

您可以通过将运算符本身编写为模板函数来解决这个问题,这样模板就可以适应不同的 rhs 类型,即

GenericMatrix<double, 1, 2>::operator*(const GenericMatrix<double, 2, 2>& rhs)

以下似乎按预期工作:

#include <array>
#include <tuple>
#include <vector>


template <typename DataType, int NumberOfRows, int NumberOfColumns>
class GenericMatrix
{
public:
    template<int N, int M>
    GenericMatrix operator * (const GenericMatrix<DataType, N, M> & rightHandSide)
    {
        //DO MATRIX MULTIPLICATION
        return GenericMatrix<DataType, NumberOfRows, NumberOfColumns>();
    }   
};


template <typename DataType>
class RotationMatrix2D : public GenericMatrix<DataType, 2, 2>
{   
};

template <typename DataType>
class Point2D : public GenericMatrix<DataType, 1, 2>
{
};


int main()
{
    RotationMatrix2D<double> rotMatrix;
    Point2D<double> point;

    point * rotMatrix; //No compiler error here

    return 0;
}

我将数字模板参数更改为 int。

您可能还想调整 return 类型的 GenericMatrix< > 模板参数以适应 returned 矩阵,但这是另一个问题。