你如何实现相互转换?

How do you implement mutual casts?

假设您有两种结构类型,一种具有 int 个成员,一种具有 float.

struct i { 
    int a, b; 
    i(int a, int b): a(a), b(b) {}
};

struct f { 
    float a, b;
    f(float a, float b): a(a), b(b) {}
};

我们要定义两个转换运算符,从 if 和相反。如果我们尝试通过运算符重载

struct i { 
    int a, b; 
    i(int a, int b): a(a), b(b) {}
    operator f() const { return f(a, b); };
};

struct f { 
    float a, b;
    f(float a, float b): a(a), b(b) {}
    operator i() const { return i(a, b); };
};

我们运行有一个声明顺序的问题,因为i需要知道ff需要知道i。此外,转换运算符必须在 类 内声明。 f 的前向声明不起作用。

有解决办法吗?

前向声明工作正常:

struct i;
struct f;

struct i
{
    int a, b; 
    i(int a, int b): a(a), b(b) {}
    operator f() const;
};

struct f
{
    float a, b;
    f(float a, float b): a(a), b(b) {}
    explicit operator i() const;
};

i::operator f() const { return f(a, b); }
f::operator i() const { return i(a, b); }