问题(C++):下面代码中成员函数(Box operator+(const Box& b))为啥可以返回box?

问题描述:

问题(C++):下面代码中成员函数(Box operator+(const Box& b))为啥可以返回box?

class Box
{
public:
    double getVolume(void)
    {
        return (length*width*height);
    }
    void setLength(double l)
    {
        length = l;
    }
    void setWidth(double w)
    {
        width = w;
    }
    void setHeight(double h)
    {
        height = h;
    }

    /* 重载+运算符,用于把两个box对象相加 */
    Box operator+(const Box& b)
    {
        Box box;
        box.length = this->length + b.length;
        box.width = this->width + b.width;
        box.height = this->height + b.height;
        return box;
    }
protected:
private:
    double length;
    double width;
    double height;
};
————————————————
版权声明:本文为****博主「透明水晶」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.****.net/I_feige/article/details/120123407

C语言 | C语言函数体返回局部变量地址发生段错误 ****问答为您找到C语言 | C语言函数体返回局部变量地址发生段错误相关问题答案,如果想了解更多关于C语言 | C语言函数体返回局部变量地址发生段错误 c语言、开发语言 技术问题等相关问答,请访问****问答。 https://ask.****.net/questions/7500398

这个是+运算符重载,目的是通过Box对象相加,实现Box对象的长宽高相加
返回值类型为Box

Box operator+(const Box& b)

返回值为box

Box boxreturn box;

建议多看看运算符重载这方面的资料

操作符可以返回自身类型,因为已经声明了Box这个类,编译器是可以识别这个类的类型,所以可以返回Box