在C++中,为什么代码示例在重载运算符时经常使用内存位置

In C++, why do code examples often use memory locations when overloading operators?

本文关键字:运算符 常使用 位置 内存 重载 C++ 为什么 代码      更新时间:2023-10-16

我在下面写了一些示例代码。

#include <iostream>
#include <cstdio>
using namespace std;   
class Box{
    int l; //length
    int b; //breadth
    int h; //height
public:
    Box(){ l =0; b = 0; h = 0;}
    Box(int d1, int d2, int d3){ l = d1;b=d2;h=d3;}
    int getLength(){return l;}
    friend Box operator+(Box b1, Box b2){
        Box tempBox;
        tempBox.l = b1.l + b2.l;
        tempBox.b = b1.b + b2.b;
        tempBox.h = b1.h + b2.h;
        return tempBox;
    }
    int calculateVolume(){ return l * b * h;}
}; 

此代码在编译/运行时不会产生错误。我们还可以将好友函数更改为以下内容:

friend Box operator+(Box &b1, Box &b2){
    Box tempBox;
    tempBox.l = b1.l + b2.l;
    tempBox.b = b1.b + b2.b;
    tempBox.h = b1.h + b2.h;
    return tempBox;

测试代码运行同样良好。我的问题是,像在朋友函数的第二个版本中那样,通过它们的内存地址引用 Box 对象"b1"和"b2"的目的是什么,这是我在示例代码中经常看到的?更重要的是,如果我们把地址传递给 friend 函数,它怎么知道在不进行任何取消引用的情况下操作存储在这些地址的对象?对不起,我对这一切有点陌生。任何帮助将不胜感激!

通过

内存地址引用 Box 对象 'B1' 和 'B2',就像在第二个版本中一样

这不是正在发生的事情。 此处不使用&的"运算符地址"伪装。

虽然从技术上讲,区别在于上下文而不是空格放置,但我们可以更清楚地编写代码如下:

friend Box operator+(Box& b1, Box& b2){

Box&是"引用Box"的类型。

引用可防止不必要的复制。阅读书中有关参考文献的章节以获取更多信息。