假设我有两个类:
// 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被定义为来自 类型的成员函数,您希望将其转换为不同的类型。签名是(在 Location
类中):
operator Point() const; // indeed takes void
// possibly operator const& Point() const;
另一种可能性是提供 converting constructor对于点
:
Point(Location const& location);
关于c++ - 运算符必须取 'void',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35541528/