c++中运算符重载时何时按引用返回或按值返回

时间:2021-03-01 19:40:56

标签: c++ operator-overloading

我无法理解何时将运算符的返回类型设置为值或引用,我有一个具有宽度和高度的类 TRectangle,我想重载 * 运算符以便我可以将一个矩形乘以一个整数,还可以重载 = 运算符,以便我可以将新值分配给另一个 TRectangle 对象。

  1. 我将 = 运算符的返回类型设置为 value,并将参数设置为 value 即使 * 运算符的返回类型是引用或值,它也能正常工作 当我将 = 的返回类型设置为引用并将参数设置为引用时,它只接受 * 运算符中的引用返回类型和引用参数。

  2. 我不知道什么时候按值或按引用返回,什么时候按值或按引用分配参数。

这是我的代码的一部分: 此代码有效

        TRectangle& operator=(TRectangle&);
        friend TRectangle& operator*(TRectangle &TR,int a); 
        friend TRectangle& operator*(int a,TRectangle &TR);
TRectangle& operator*(TRectangle &TR,int a)
{
    TR.La=TR.La*a;  // sets width of rectangle 
    TR.Lo=TR.Lo*a;  // sets height of rectangle 
    return TR;
}

TRectangle& operator*(int a,TRectangle &TR)
{
    return TR*a;  //uses the already overloaded * operator above
}

TRectangle& TRectangle::operator=(TRectangle& TR)
{
    La=TR.getLa();
    Lo=TR.getLo();
    
    return *this;
}

这个也有效(我在 = 运算符中将返回类型和参数更改为值) 我保留了 * 运算符:

TRectangle operator=(TRectangle);
TRectangle TRectangle::operator=(TRectangle TR)
{
    La=TR.getLa();
    Lo=TR.getLo();
    
    return *this;
}

即使将所有运算符的返回类型设置为值,此方法也能正常工作:

        TRectangle operator=(TRectangle);
        friend TRectangle operator*(TRectangle &TR,int a); 
        friend TRectangle operator*(int a,TRectangle &TR);
TRectangle operator*(TRectangle &TR,int a)
{
    TR.La=TR.La*a;  // sets width of rectangle 
    TR.Lo=TR.Lo*a;  // sets height of rectangle 
    return TR;
}

TRectangle operator*(int a,TRectangle &TR)
{
    return TR*a;  //uses the already overloaded * operator above
}

TRectangle TRectangle::operator=(TRectangle TR)
{
    La=TR.getLa();
    Lo=TR.getLo();
    
    return *this;
}

现在我很困惑何时使用按引用或值返回并按引用或值分配参数以及何时在参数中使用 const ,有时当我不使用 const 时它不会' t 使用返回类型的引用。

0 个答案:

没有答案
相关问题