c++ - 你如何实现相互转换?
问题描述
假设您有两种结构类型,一种带有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 i
tof
和 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
需要知道f
和f
需要知道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); }
推荐阅读
- python - 在我的程序中使用 pyttsx3 时出现错误
- swift4 - 无法从服务器下载 PKpass
- flask - 我可以限制到 Flask 中特定端点的并发连接数吗
- javascript - 初始化后显示 [object Object] 的价格滑块
- javascript - 从 VueJS 组件中的另一个文件调用 JS 函数
- laravel - 查询函数在laravel中返回结果
- angular - 我正在从 8 到 9 进行角度迁移,碰巧我有这个错误 TS2339: Property 'get' does not exist on type 'unknown'
- javascript - 在 Navigation React Native 中传递值
- c++ - Move overload and destructor theory. Can someone please answer if I'm right?
- node.js - 如何从节点访问虚拟文件夹(windows)