C++ 如何将内置类型转换为用户定义类型

C++ 如何将内置类型转换为用户定义类型,c++,conversion-operator,C++,Conversion Operator,我有一个叫做BigInteger的类,它支持大整数运算。我想实现BigInteger和内置类型“int”之间的混合运算。换句话说,我想支持以下陈述 BigInteger a(10); a + 10; 10 + a; 我知道重载函数可以处理它 BigInteger operator +(const BigInteger&, const int&); BigInteger operator +(const int&, const BigInteger&); 此外,

我有一个叫做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;
}
#包括
使用名称空间std;
类BigInteger
{
公众:
BigInteger(常量int&i)
{

cout您需要添加将从int中获取
biginger
值的构造函数

BigInteger (const int& value)

因此,创建一个构造函数
biginger(int)
,并定义一个
biginger操作符(const-biginger&lhs,const-biginger&rhs)

确保您只从
int
转换到
biginger
,而不是反向转换。或者,如果反向转换会导致溢出,则引发异常。

您应该为
biginger操作符+(biginger const&,int)实现重载正如萨特和Andrei Alexandrescu在C++代码标准中所写的(第29条),你应该“考虑重载以避免隐式的对话”。在这个特殊的情况下,你的大整数可能使用运算符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;
}

定义构造函数BigInteger(int)并重载运算符BigInteger运算符+(const BigInteger&left,const BigInteger&right).

它能比重载op+简单多少?关于自由函数和成员函数之间的区别:。简言之,优先选择自由函数,使
int+biginger
biginger+int
同等工作(对于成员函数,前者不起作用)顺便说一下,C++中有隐式和显式转换运算符吗?例如,在Delphi中,可以定义隐式和显式转换的不同行为。@ SpOK它们是新的。参见C++中显式构造函数的解释链接。但您仍然不能并排引用和解释。为什么我不能使用成员Fu?nction?这不是我想要解释的,但你可以。谢谢!顺便问一下,让
biginger操作符+(biginger lhs,int rhs)
成为朋友函数更好吗?