是否可以在头文件中重载运算符(声明 class 时)?

Is it OK to overload operators inside the header file (when declaring the class)?

Test.h:

class Test {
private:
    int value;

public:
    Test();
    int getValue();
    void setValue(int value);

    bool operator >(Test &l) {
        if (value > l.value) {
            return true;
        }
        return false;
    }
};

这会导致任何问题吗?如果是,将它实现到 cpp 文件中的正确方法是什么?如果我试图将它实现到一个 cpp 文件中,我会收到一条错误消息,指出参数的数量(因为该函数现在不在 class 中?)。

我想说,对于这些微不足道的函数,这是实现它的理想方式,因为它允许编译器内联它们,从而消除了函数开销。

但是您应该尽可能使函数 const

所以:

class Test {
private:
    int value;

public:
    Test();
    int getValue();
    void setValue(int value);

    bool operator >(const Test &l) const { // be const correct!
        if (value > l.value) {
            return true;
        }
        return false;
    }
};

该函数根本不修改数据成员,所以我将其标记为 const。参数也没有改变,所以我也标记了 const.

如果您 想将它实现到一个单独的 cpp 文件中,那么您需要使用 class 名称对其进行限定:

Test.h

class Test {
private:
    int value;

public:
    Test();
    int getValue();
    void setValue(int value);

    bool operator >(const Test &l) const; // declare only
};

Test.cpp

// Qualify the name with Test::
bool Test::operator >(const Test &l) const { // be const correct!
    if (value > l.value) {
        return true;
    }
    return false;
}

你也可以简洁这些功能:

// Qualify the name with Test::
bool Test::operator >(const Test &l) const { // be const correct!
    return value > l.value;
}

理论上,您应该使 class 对象尽可能小,并在相关的 非成员 函数中尽您所能。我怀疑你被咬的区别是 class 中定义的非静态成员函数总是有一个 'invisible' first/last 参数(this 指针)。您可能会忘记这一点,但编译器不会...