我试图创建一个重载的一元运算符,但是无法编译代码。该代码的简化版本如下:-

class frag
{
    public:

        frag myfunc  (frag oper1,
                      frag oper2);
        frag myfunc2  (frag oper1,
                      frag oper2);

        friend frag operator + (frag &oper1,
                                frag &oper2);

        frag operator - ()
        {
            frag f;
            f.element = -element;
            return f;
        }

    private:

        int element;

};

frag myfunc (frag oper1, frag oper2)
{
    return oper1 + -oper2;
}

frag myfunc2 (frag oper1, frag oper2)
{
    return oper1 + oper2;
}

frag operator+ (frag &oper1, frag &oper2)
{
    frag innerfrag;
    innerfrag.element = oper1.element + oper2.element;
    return innerfrag;
}

编译器报告...
/home/brian/Desktop/frag.hpp: In function ‘frag myfunc(frag, frag)’:
/home/brian/Desktop/frag.hpp:41: error: no match for ‘operator+’ in ‘oper1 + oper2.frag::operator-()’
/home/brian/Desktop/frag.hpp:16: note: candidates are: frag operator+(frag&, frag&)

有人可以建议我在这里需要做什么吗?

最佳答案

常量正确性

这一定是

 frag operator+ (const frag &oper1, const frag &oper2);

否则操作数不能是临时的,例如operator-的返回值

一元减应为:
frag operator - () const;

因为它不应该修改操作数。

09-07 08:00