运营商必须采取'无效'

时间:2016-02-21 20:19:53

标签: c++ class conversion-operator

假设我有两个类:

// 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;

所以,我在operator内添加了Point

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

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

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

听起来好像编译器希望操作符不接受任何参数,但这似乎并不正确 - 除非我错误地使用了操作符。这个错误背后的真正含义是什么?

2 个答案:

答案 0 :(得分:4)

User-defined conversions operators被定义为来自成员函数,您希望将其转换为其他类型。签名是(Location类内):

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

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

Point(Location const& location);

答案 1 :(得分:0)

不要使运算符()过载。你想要做的是创建一个有点意义的自定义构造函数。编译器在执行赋值时调用this或重载赋值运算符。

   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;