运营商必须采取 'void'

Operator must take 'void'

假设我有两个 类:

// A struct to hold a two-dimensional coordinate.
struct Point
{
    float x;
    float y;
};

// A struct identical to Point, to demonstrate my problem
struct Location
{
    float x;
    float y;
};

我想将 Location 隐式转换为 Point:

Point somePoint;
Location someLocation;

somePoint = someLocation;

所以,我在 Point 中添加了这个 operator:

operator Point(Location &other)
{
    // ...
}

于是我在 Debian 上使用 g++ 4.9.2 编译,并收到此错误:

error: 'Point::operator Point(Location &other)' must take 'void'

听起来编译器希望运算符不接受任何参数,但这似乎不对——除非我错误地使用了运算符。这个错误背后的真正含义是什么?

User-defined conversions operators 被定义为 成员函数 类型 from ,您要将其转换为不同的类型。签名是(在 Location class 内):

operator Point() const; // indeed takes void
// possibly operator const& Point() const;

另一种可能性是为Point提供converting constructor:

Point(Location const& location);

不要重载 operator()。您要做的是创建一个带点的自定义构造函数。当您进行赋值或重载赋值运算符时,编译器会调用它。

   Location( Point& p){
            x = p.x;
            y = p.y;
   }

   Location& operator= ( Point& p){
            x = p.x;
            y = p.y;
            return *this;
   }

这将使它编译

  Point somePoint;
  Location someLocation;

  somePoint = someLocation;
  Location loc = somePoint;