【问题标题】:Operator overloading of "basic" classes“基本”类的运算符重载
【发布时间】:2013-05-12 18:14:06
【问题描述】:

您好,我想将一个矩阵乘以左边的一个数字,例如:N=a*M 其中 a 是一个数字。

如果我想在右边相乘,我会简单地在我的矩阵类中重载运算符 *。 但是在这种情况下我该怎么办?即使它是“默认”类,我也可以重载 float 的运算符 * 吗? (我什至不确定这是一个类)

【问题讨论】:

    标签: c++ matrix overloading operator-keyword


    【解决方案1】:

    您必须根据另一个来定义功能。例如:

    Matrix operator *(float x, Matrix const& m)
    {
        return m * x;
    }
    

    【讨论】:

    • 所以我可以在类定义之外重载运算符?太好了!
    • @user2370139 是的,这是一个全局运算符定义。但至少有一个操作数必须是类类型。
    • 返回值不应该是矩阵吗?
    【解决方案2】:

    重载 * 运算符以在乘以常数后返回矩阵。

    matrix  matrix :: operator* (int a)
    {
       matrix temp(x, y);
        int num,num1, num2;
        A = new int *[temp.x];
        for (num=0; num<=temp.x; num++)
        {
            A[num] = new int [temp.y];
        }
            for (num1=0; num1<temp.x; num1++)
        {
            for (num2=0; num2<temp.y; num2++)
            {
                temp.A[num1][num2] = 0;
            }
        }
        int i, j;
        for ( i = 0; i < x; i++)
        {
            for ( j = 0; j < y; j++)
    
            {
    
                temp.A[i][j] = a * A[i][j];
            }
        }
        return (temp);
    }
    

    参考这个例子matrix multiply by number

    【讨论】:

    • 这不是他要求的。他想要结合算术。
    猜你喜欢
    • 2019-11-17
    • 2013-02-05
    • 1970-01-01
    • 2017-10-29
    • 2018-06-16
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多