2017-05-07 101 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