【问题标题】:Operator Overloading using friend functions in C++在 C++ 中使用友元函数的运算符重载
【发布时间】:2018-08-14 00:40:15
【问题描述】:

我有以下 Point 类。

#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。我是否在错误的地方声明了友元函数或在错误的地方提供了实现?

【问题讨论】:

    标签: c++ operator-overloading friend


    【解决方案1】:

    如果函数定义在将包含在多个 .cpp 文件中的头文件中,则需要将它们标记为 inline。要么将定义(实现)移动到 .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】:

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

      来自CPP reference

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

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

      【讨论】:

        猜你喜欢
        • 2011-03-19
        • 2017-07-26
        • 1970-01-01
        • 2016-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多