【问题标题】:Using multiple operators with operator overloading gives strange error使用带有运算符重载的多个运算符会产生奇怪的错误
【发布时间】:2019-02-14 22:49:39
【问题描述】:

我有一个名为 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 没有。

很奇怪..

【问题讨论】:

  • this->two = &two的原因是什么?为什么要使用指针?这个指针是否会被存储? DivideOperation 对象并在很久以后使用(当它们指向的对象超出范围或被破坏时)?为什么指向frontOp?这种动态分配看起来像是内存泄漏。
  • 是的,this->two = two 不是必需的。我将删除它,我正在使用frontOp 的指针,因为我需要存储对 floatTensor 所经过的操作的引用。这些信息将在以后使用。在函数头中的 FloatTensor 2 前面添加 const 不是一个选项,因为以后可以更改指针。

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


【解决方案1】:

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

FloatTensor operator + (const FloatTensor &two)

【讨论】:

  • 我不能让它成为常量,因为 2 的值可以在以后更改。有没有办法解决这个问题,同时保留两个非常量。或者只为临时保留它 const 而不是说 ``` x1*w1```
  • 您可以为非临时人员提供非const 重载。
猜你喜欢
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 2018-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多