当我们进行运算符重载时,这两段代码有什么区别?

What is difference between these two pieces of code when we do operator overloading?

代码 1:

class CVector {
public:
    int x, y;
    CVector() {};
    CVector(int a, int b) :x(a), y(b) {}
};

CVector operator- (const CVector& lhs, const CVector& rhs)
{
    CVector temp;
    temp.x = lhs.x - rhs.x;
    temp.y = lhs.y - rhs.y;
    return temp;
}

int main()
{
    CVector foo(2, 3);
    CVector bar(3, 2);
    CVector result;
    result = foo - bar;
    cout << result.x << ',' << result.y << endl;
}

代码 2:

class CVector {
public:
    int x, y;
    CVector() {};
    CVector(int a, int b) :x(a), y(b) {}
};

CVector operator- (const CVector& lhs, const CVector& rhs)
{
    return CVector(lhs.x - rhs.x, lhs.y - rhs.y);
}

int main()
{
    CVector foo(2, 3);
    CVector bar(3, 2);
    CVector result;
    result = foo - bar;
    cout << result.x << ',' << result.y << endl;
}

这两段代码的操作相同。我想知道为什么我们可以写CVector(lhs.x - rhs.x, lhs.y - rhs.y)。这是什么意思?当我们使用没有名字的 class 时会发生什么?

why we can write CVector(lhs.x - rhs.x, lhs.y - rhs.y). What does it mean? What happens when we use a class without a name?

表达式 CVector(lhs.x - rhs.x, lhs.y - rhs.y) 使用 参数化构造函数 CVector::CVector(int, int) 通过传递参数 lhs.x - rhs.xlhs.y - rhs.y。就像 CVector foo(2, 3); CVector bar(3, 2) 使用参数化构造函数一样,表达式 CVector(lhs.x - rhs.x, lhs.y - rhs.y) 也使用参数化构造函数。

您可以通过在参数化构造函数中添加一个 cout 来确认这一点,如下所示:

#include <iostream>

class CVector {
public:
    int x, y;
    CVector() {};
    CVector(int a, int b) :x(a), y(b) {
        std::cout<<"paremterized ctor used"<<std::endl;
        }
};

CVector operator- (const CVector& lhs, const CVector& rhs)
{
    return CVector(lhs.x - rhs.x, lhs.y - rhs.y); //this uses the parameterized ctor
}

int main()
{
    CVector foo(2, 3);
    CVector bar(3, 2);
    CVector result;
    result = foo - bar;
    std::cout << result.x << ',' << result.y << std::endl;
}

上述程序的output为:

paremterized ctor used
paremterized ctor used
paremterized ctor used
-1,1

注意在上面显示的输出中,对参数化 ctor 的第三次调用是由于 return 语句 return CVector(lhs.x - rhs.x, lhs.y - rhs.y);