c++ - 在重载函数中按引用传递对象与按值传递对象

标签 c++

我一直在读到,在重载运算符函数时,最好通过引用传递,通常是出于性能原因。但是我注意到,当我按值传递对象时,它仍然具有相同的效果。不应该按值传递它不影响运算符(operator)吗?我知道如果你有两个 int 变量并且你想通过将它们传递给另一个函数来交换它们,那么它只有在你通过引用传递(或者如果你传递一个指针)时才有效。如果你只是传值,最后变量保持不变。那么不应该同样适用于传递类对象吗?

例子:

Person Person::operator+(Person obj1){
    Person sum;
    sum.age = this->age + obj1.age;

    return sum;
} 

如果我有一个 main 并做:

Person person1(14);
Person person2(182);
Person3 = person1 + person2;
std::cout << person3.age << std::endl;

和我做的一样

Person Person::operator+(Person &obj1){
    Person sum;
    sum.age = this->age + obj1.age;

    return sum;
} 

所以我有点像在我提到的交换方法中那样思考这个问题。如果我将值传递给交换函数,它不会更改变量的原始值。我在想,如果我只是传递对象而不是引用,它实际上不会改变重载运算符。现在我在想,既然在我的 Person 类中,运算符和变量都在同一个类中定义,那么这就不适用了,这就是为什么它实际上会重载运算符?

最佳答案

您定义的两个 operator+ 重载都返回一个年龄值为 196 的 Person 对象(这是我的值,除了您的输出应该是)。这两种方法都不尝试修改传入的值(通过隐式 this 指针)。我试图通过直接在下面的每个方法中的评论来说明原因。

在第一个运算符+中:

Person Person::operator+(Person obj1){

    // We have access to Person1 via the implicit this pointer.
    // obj1 is a copy of Person2. Hence, we have no access to Person2.

    Person sum;

    // The next statement only reads from the 2 objects.
    sum.age = this->age + obj1.age;

    // New object returned without any side effects to Person1 or Person2.
    return sum;
}

在第二个运算符+中:

Person Person::operator+(Person &obj1){
    // We have access to Person1 via the implicit this pointer.
    // We have access to Person2 by obj1.

    Person sum;

    // The next statement only reads from the 2 objects.
    sum.age = this->age + obj1.age;

    // New object returned without any side effects to Person1 or Person2.
    return sum;
}

您可以通过修改两个方法签名来向自己证明这一点:

Person Person::operator+(Person obj1) const
Person Person::operator+(const Person &obj1) const

现在这两种方法都不允许修改添加的值。

您给出的关于需要通过引用或指针传递以使交换工作的交换示例是这样的,因为交换必须修改正在交换的对象。在 Person 示例中,operator+ 只需要返回一个新的 Person 对象,该对象具有通过添加两个 Person 对象获得的正确值。

在您的示例中,您应该更喜欢通过 const 引用传递,因为它会跳过复制 Person2 的开销(因为它在第一种方法中必须这样做)。如果您需要在方法主体中复制传入的参数,这个答案会有所改变。但在这里你没有。

关于c++ - 在重载函数中按引用传递对象与按值传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597858/

相关文章:

c++ - C++调用抽象基类的构造函数

c++ - set_intersection在范围范围内

c++ - 这是编写析构函数的正确方法吗?

python - Cython 为高频控制循环传递 float 的最快方法

c++ - OpenCL 在调用 clGetPlatformIDs 时返回 -64

c++ - MongoDb 总和聚合 C++

c++ - 使用/usr/lib/i386-linux-gnu 而不是/usr/lib/x86_64-linux-gnu 在 CMake 中查找库

c++ - 如何管理从 C++ 返回到 QML 的 QObject 的生命周期?

c++ - 未收到确认时如何进行数据包重试

c++ - 溢出/下溢问题?