将多个运算符与运算符重载一起使用会产生奇怪的错误

时间:2019-02-13 13:03:54

标签: c++ c++11 operator-overloading

我有一个名为FloatTensor的类。在那我已经为+和*重载了运算符。这是代码。


class FloatTensor {
    public:
    float val; // value of tensor 
    float grad; // value of grad
    Operation *frontOp =NULL, *backOp =NULL;
    FloatTensor* two;
    FloatTensor() {
        // default
    }

    FloatTensor(float val) {
        this->val = val;
    }

    FloatTensor(float val, Operation* op) {
        this->val = val;
        this->backOp = op;
    }

    void backward(float grad) {
        this->grad = grad;
        if(this->backOp != NULL) {
            this->backOp->backward(grad);
        }
    }
    FloatTensor exp() {
        this->frontOp = new ExponentOperation(this);
        return this->frontOp->compute();
    }

    FloatTensor operator * (FloatTensor &two) { 

        this->frontOp = new MultiplyOperation(this, &two);
        return this->frontOp->compute();
    }

    FloatTensor operator + (FloatTensor &two) { 
        this->frontOp = new AddOperation(this, &two);
        return this->frontOp->compute();
    }

    FloatTensor operator / (FloatTensor &two) { 

        this->frontOp = new DivideOperation(this, &two);
        return this->frontOp->compute();
    }

};

在我的主要功能中,当我尝试简单的重载时,一切运行良好

int main() {

    // X 
    FloatTensor x1(200); // heap declaration
    FloatTensor x2(300);

    // Weights
    FloatTensor w1(222);
    FloatTensor w2(907);

    FloatTensor temp = (x1*w1);

}

但是,当我尝试使用更多这样的运算符重载此公式

int main() {

    // X 
    FloatTensor x1(200); // heap declaration
    FloatTensor x2(300);

    // Weights
    FloatTensor w1(222);
    FloatTensor w2(907);

    FloatTensor temp = (x1*w1) + (x2*w2);

}

我收到此错误:

no operator "+" matches these operands -- operand types are: FloatTensor + FloatTensor

如果有人能解释为什么会发生,我将不胜感激。我观察到这可行:

x1*w1*x2*x1;
x1*w1 + x2;

但是x1*w1 + x2*w2没有。

很奇怪..

1 个答案:

答案 0 :(得分:3)

您的运算符接受非const左值引用作为参数。临时不会绑定到非const左值引用。要接受临时人员,请使用:

FloatTensor operator + (const FloatTensor &two)