0

假设我有两个类:

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

我想将 a 隐式转换Location为 a Point

Point somePoint;
Location someLocation;

somePoint = someLocation;

所以,我operator在里面添加了这个Point

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

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

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

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

4

2 回答 2

4

用户定义的转换运算符被定义为要转换为不同类型的类型成员函数。签名是(类内):Location

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

另一种可能性是为提供转换构造函数Point

Point(Location const& location);
于 2016-02-21T20:22:34.020 回答
0

不要重载 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;
于 2016-02-21T20:37:54.463 回答