首页 > 解决方案 > 你如何实现相互转换?

问题描述

假设您有两种结构类型,一种带有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) {}
};

我们要定义两个强制转换运算符,from itof和 conversely。如果我们尝试通过运算符重载来做到这一点

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不起作用。

有解决办法吗?

标签: c++typecasting-operator

解决方案


前向声明工作正常:

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

推荐阅读