gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:44:56 27 4
gpt4 key购买 nike

我有一个名为 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)

关于c++ - 如何将内置类型转换为用户定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16011405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com