c++ - 运算符必须取 'void'

标签 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;

所以,我在 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/

相关文章:

C++ STL 优先级队列客户比较器不起作用

javascript - 在 typescript 中扩展方法

c++ - 在 C++ 中重载运算符时,为什么 T* 优于 bool?

c++ - 转换运算符作为独立函数

c++ - 包装数组的类的转换与下标运算符重载

c++ - 无法将迭代器传递给 C++ 中的类方法

c++ - 为什么函数重载会在 C++ 中产生模棱两可的错误?

css - @font-face 只能在本地工作

php - 没有类的 php 站点的 UML 类图

c++ - 静态数据成员的模板特化