![](/img/trans.png)
[英]How to make a user-defined type initialize *exactly* like a built-in type?
[英]how to convert a built-in type to user-defined type
我有一个叫做BigInteger的类,它支持大整数运算。 我想在BigInteger和内置类型'int'之间实现混合操作。 换句话说,我想支持以下陈述
BigInteger a(10);
a + 10;
10 + a;
我知道重载函数可以处理它
BigInteger operator +(const BigInteger&, const int&);
BigInteger operator +(const int&, const BigInteger&);
此外,我知道转换运算符只能处理它,
operator int();
但是以上函数支持将BigInteger转换为int,这将失去精度 。 我正在寻找一些比重载函数更简单并保持精度的方法。
感谢大家。
我试试看
#include <iostream>
using namespace std;
class BigInteger
{
public:
BigInteger(const int& i)
{
cout << "construct: " << i << endl;
val = i;
}
// BigInteger operator +(const BigInteger& tmp) const
// {
// return BigInteger(val + tmp.val);
// }
friend ostream& operator <<(ostream& os, const BigInteger& bi)
{
os << bi.val << endl;
return os;
}
int val;
};
BigInteger operator +(const BigInteger& a, const BigInteger& b)
{
return BigInteger(a.val + b.val);
}
int main(int argc, const char *argv[])
{
BigInteger a(12);
cout << (a + 123) << endl;
cout << (1231 + a) << endl;
return 0;
}
为什么不能使用成员函数? 这个怎么运作?
您需要添加构造函数,该构造函数将从int中获取BigInteger
值
BigInteger (const int& value)
因此,构造一个BigInteger(int)
构造函数,并定义一个BigInteger operator(const BigInteger &lhs, const BigInteger &rhs)
。
您应该为BigInteger operator+(BigInteger const&, int);
实现重载BigInteger operator+(BigInteger const&, int);
正如Herb Sutter和Andrei Alexandrescu在C ++ Coding Standarts(条款29)中所写的那样,您应该“考虑重载以避免隐式类型对话”。 您的BigInteger可能会使用new运算符进行构造,在这种特殊情况下可以避免。 另外,您应该根据一元运算实现二进制运算:
class BigInteger {
// ..
public:
BigInteger& operator+=(int); // this operation can reuse BigIntegers buffer
// ..
}
BigInteger operator+(BigInteger lhs, int rhs)
{
return lhs+=rhs;
}
BigInteger operator+(int lhs, BigInteger rhs)
{
return rhs+=lhs;
}
确保只将int
转换为BigInteger
,绝不要反向转换。 或者,如果反向转换会导致溢出,则引发异常。
定义构造函数BigInteger(int)并重载运算符BigInteger运算符+(const BigInteger&left,const BigInteger&right)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.