在 C++ 中使用友元函数进行运算符重载

Operator Overloading using friend functions in C++

我有以下几点class。

#ifndef POINT_HPP
#define POINT_HPP

#include <string>

class Point {

private:

    double m_x, m_y;

public:

    Point();
    Point(double x, double y);
    Point(const Point &p);

    ~Point();

    // selectors
    double X() const;
    double Y() const;
    std::string ToString() const;
    double Distance() const;
    double Distance(const Point &p) const;

    // modifiers
    void X(double x);
    void Y(double y);

    Point operator - () const; // Negate coordinates
    //Point operator * (double factor) const; // Scale the coordinates.
    Point operator + (const Point & p) const; // Add coordinates.
    bool operator == (const Point & p) const; // equally compare 
operator.

    Point& operator = (const Point& source);
    Point& operator *= (double factor);

    // non member function to facilitate commutative 
multiplication
    friend Point operator * (double factor, const Point & p);
    friend Point operator * (const Point & p, double factor);

};

Point operator * (double factor, const Point & p) {
    return Point(p.m_x * factor, p.m_y * factor);
}

Point operator * (const Point & p, double factor) {
    return factor * p;
}

#endif //POINT_HPP

创建两个 Point 对象并尝试使用实现的 * 运算符执行乘法时。我收到多重定义错误。我相信我的 * 运算符已过载,以便我可以按任何顺序执行 double * Point object 和 Point object * double 。我是不是在错误的地方声明了友元函数或者在错误的地方提供了实现?

如果函数是在将包含在多个 .cpp 文件中的头文件中定义的,则需要将它们标记为 inline。或者将定义(实现)移动到 .cpp 文件中。每个以现在的方式包含头文件的 .cpp 文件都在创建一个定义,当它们全部链接在一起时,您将拥有 "multiple definitions"

inline Point operator * (double factor, const Point & p) {
    return Point(p.m_x * factor, p.m_y * factor);
}

inline Point operator * (const Point & p, double factor) {
    return factor * p;
}

允许在class中定义友元函数。这样做会使它们内联。

来自CPP reference

A function defined entirely inside a class/struct/union definition, whether it's a member function or a non-member friend function, is implicitly an inline function.

如果这样做,就可以避免多重定义问题。