C++自定义类型
问题描述:
我有一个类int32
,它的设置方式基本上与int
(运算符重载)接口,但有一部分我不明白。C++自定义类型
int32 i32 = 100; // Works
int i = 200; // Works
i32 += 10; // Works
i32 -= 10; // Works, i32 = 100 right now
i = i32; // Doesn't work
我需要什么运营商超载达到参考123-132返回它的存储值,在这种情况下,100(或怎么回事能不能做到)?
答
你可以添加一个conversion operatoroperator 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);
+0
这完美地描述了我想要达到的目标!谢谢。 –
答
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);
记:你shold不写转换操作符来诠释,因为没有保函int
是32位。
答
在你的int32类中实现一个转换运算符。
class int32
{
// conversion operator
operator int() const
{
int ret = // your logic
return ret;
}
}
这种转换操作员将基本类型(INT)转换为你定义的类型INT32;
请发布[MCVE]! –
@πάνταῥεῖ我认为这就足够了..你想让我发布整个int32的源代码吗? –
不知道int32是什么,没有人不知道问题实际上是什么。 –