【发布时间】: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