【问题标题】:How do you implement mutual casts?你如何实现相互转换?
【发布时间】:2019-07-27 19:47:23
【问题描述】:

假设您有两种结构类型,一种是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 的前向声明不起作用。

有解决办法吗?

【问题讨论】:

  • 您的代码有很多语法错误。如果你修复它们,前向声明就会起作用。
  • 强制转换运算符必须返回它强制转换的类型而不是其他类型...所以它不是 int() 而是 i()!
  • 我现在已经修正了错别字。问题是“use of undefined type 'f'”。

标签: c++ typecasting-operator


【解决方案1】:

前向声明可以正常工作:

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

【讨论】:

  • 我明白了,你必须拆分声明/定义。
  • @YvesDaoust:是的,对于所有相互依赖的类型都是如此。转化并不特殊。
  • 顺便说一句:f::operator i() 不需要拆分,因为此时 i 是已知的
  • @Klaus:如果您的意思是“不需要”,那是真的。但是“must not”的意思是“不被允许”——这不是“must”的否定。
  • @YvesDaoust:不!编译器足够聪明,知道何时内联是最佳优化选项。如果定义在类范围之外的头文件中,您只需要使用 inline 以避免多个定义的链接器错误原因。提示编译器将代码内联到调用者上下文中的关键字的含义已完全过时。 en.cppreference.com/w/cpp/language/inline
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
相关资源
最近更新 更多