【问题标题】:C++ custom typeC++ 自定义类型
【发布时间】:2016-10-07 05:08:51
【问题描述】:

我有一个类 int32,它的设置方式基本上可以作为 int 接口(运算符重载),但有一部分我不明白。

int32 i32 = 100; // Works
int i = 200; // Works
i32 += 10; // Works
i32 -= 10; // Works, i32 = 100 right now
i = i32; // Doesn't work

我需要重载什么运算符来实现引用 i32 返回它的存储值,在本例中为 100(或者它可以如何完成)?

【问题讨论】:

  • @πάνταῥεῖ 我认为这就足够了.. 你希望我发布int32 的全部来源吗?
  • 在不知道 int32 是什么的情况下,没有人知道问题到底是什么。
  • @JosephCaruso,整个课程 i32 是不必要的。你必须展示足够多的代码来说明你认为它应该工作的原因。
  • 重载转换运算符为int类型。

标签: c++ operator-overloading custom-type


【解决方案1】:

您可以添加conversion operator operator int:

class int32 {
public:
    operator int() const;
    ...
};

请注意,它有两种口味。以上将允许

int32 foo;
int i = foo;

如果将转换运算符定义为explicit

    explicit operator int() const;

那么上面的设计将失败,并且需要显式转换:

int32 foo;
int i = static_cast<int>(foo);

【讨论】:

  • 这完美地描述了我想要实现的目标!谢谢。
【解决方案2】:
class int32{
private:
    std::int32_t value;
public:
    constexpr /*explicit*/ operator std::int32_t() const noexcept { return this->value; }
};

你应该写转换运算符。

int32 a = 1;
std::int32_t b = a;//OK

但是,指定explicit并强制转换是有害的。

int32 a = 1;
//std::int32_t b = a;//NG
std::int32_t b = static_cast<std::int32_t>(a);

注意:您不应将转换运算符写入 int,因为无法保证 int 是 32 位。

【讨论】:

    【解决方案3】:

    在您的 int32 类上实现转换运算符。

    class int32
    {
        // conversion operator
        operator int() const
        { 
            int ret = // your logic
            return ret;
        }
    }
    

    此转换运算符会将原始类型 (int) 转换为您定义的类型 int32;

    【讨论】:

      猜你喜欢
      • 2015-12-31
      • 1970-01-01
      • 2012-12-14
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      相关资源
      最近更新 更多