代码之家  ›  专栏  ›  技术社区  ›  Mutating Algorithm

C++中用Fuffic函数实现运算符重载

  •  0
  • Mutating Algorithm  · 技术社区  · 6 年前

    我有下面的重点课。

    #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
    

    当创建两点对象并尝试与实现的 * *

    2 回复  |  直到 6 年前
        1
  •  2
  •   xaxxon    6 年前

    它们需要标记 inline 如果函数是在头文件中定义的,该头文件将包含在多个.cpp文件中。或者将定义(实现)移动到.cpp文件中。包括头文件的每个.cpp文件现在的方式是创建一个定义,当它们都链接在一起时,就有了“多个定义”

    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;
    }
    
        2
  •  2
  •   P.W    6 年前

    允许在类中定义friend函数。这样做会使它们内联。

    CPP reference

    完全在类/结构/联合定义中定义的函数,无论是成员函数还是非成员友元函数,都是隐式内联函数。

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