2017-05-07 99 views
-3

我必须在C++中构建一个BigInteger类。 BigInt必须存储在一个固定大小的数组中。我现在想知道,是否有可能将赋值运算符重载为接受右侧的long long int数字(但将内部整数存储在数组中)。C++ BigInteger和赋值操作符重载

实施例:

的BigInteger I = 1000000000000000010000000000000000010000000000000000100000000000;

和国内它可以被存储,如:

i.data = {10000000000000000,100000000000000000,10000000000000000,100000000000};

这可能吗?这是多远我来:

#include "BigIntegerF.h" 
using namespace std; 

// Default Constructor 
BigIntegerF::BigIntegerF() { 
    data[0] = 0; 
} 

// Destructor 
BigIntegerF::~BigIntegerF(){} 

BigIntegerF& BigIntegerF::operator = (const BigIntegerF& bigInt) 
{ 
    // don't know how i could implement it here 
} 
+1

你试过吗?你知道如何重载'operator ='吗?如果是,那么你面临的问题是什么? – UnholySheep

+1

请注意:您可能不希望覆盖赋值运算符,复制构造函数,析构函数等。这也被称为“零规则”,在[这里]解释(http://en.cppreference.com/w/cpp/language/rule_of_three)。 – anatolyg

回答

2

你可以用user-defined literals做到这一点:

BigInteger operator ""_bigInt(char const *str, std::size_t len) { 
    // Create and return a BigInteger from the string representation 
} 

然后你就可以创建一个BigInteger如下:

auto myBigInt = 1234567890_bigInt; 
-1

C++有operator ""语法正是这些情况,您希望从代码中的文字中创建用户定义的对象(请参阅answer by Quentin)。

如果你的编译器不支持较新的operator ""语法(如MS Visual Studio的2013及以上),你可以用略少方便的语法,它涉及到一个初始化列表:

class BigInteger 
{ 
public: 
    ... 

    BigInteger(std::initializer_list<unsigned long long> list) 
    { 
     std::copy(list.begin(), list.end(), data); 
     size = list.size(); 
    } 

private: 
    ... 
    unsigned long long data[999]; 
    size_t size; 
}; 

使用它如下:

BigInteger i{100000, 2358962, 2398572389, 2389562389}; 
+0

“如果你的编译器不支持相对较新的操作符语法(例如MS Visual Studio)” - Visual Studio(至少2015和2017)支持用户定义的文字就好了。 –

+0

更新了细节 – anatolyg