>假设我有两个类:
// 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'
听起来编译器希望运算符不接受任何参数,但这似乎不对 - 除非我错误地使用了运算符。此错误背后的真正含义是什么?
用户定义的转换运算符定义为要从中转换为其他类型的类型的成员函数。签名是(在类Location
内部):
operator Point() const; // indeed takes void
// possibly operator const& Point() const;
另一种可能性是为Point
提供一个转换构造函数:
Point(Location const& location);
不要重载运算符()。您要做的是创建一个获取点的自定义构造函数。编译器在执行赋值或重载赋值运算符时调用此函数。
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;